How to subtract two array lists in Java

0

list1.removeAll(list2); will do the job, but it cost you N1*N2 operations .
If you work with big arrays you can improve performance like this:

public <T> List<T> subtract(List<T> list1, List<T> list2) {
		List<T> result = new ArrayList<T>();
		Set<T> set2 = new HashSet<T>(list2);
		for (T t1 : list1) {
			if( !set2.contains(t1) ) {
				result.add(t1);
			}
		}
		return result;
	}

Leave a Reply

© 2010 Developer Articles. All rights reserved.
Powered by: Aaban Technologies