/* * main method to try them out */ public static void main(String[] args) { List animals = new ArrayList(); List excluded = new ArrayList(); for (int i = 0; i < 40; i++) { ProcessAnimal animal = new ProcessAnimal(); animal.setInternalId(i); animals.add(animal); } for (int i = 0; i < 10; i++) { ProcessAnimal animal = new ProcessAnimal(); animal.setInternalId(i++); i++; excluded.add(animal); } long start = System.currentTimeMillis(); for (int i = 0; i < 20000; i++) { List incl = testLists1(animals, excluded); // System.out.println("Incl.size " + incl.size()); } System.out.println("Time spent1: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < 20000; i++) { List incl = testLists2(animals, excluded); // System.out.println("Incl.size " + incl.size()); } System.out.println("Time spent2: " + (System.currentTimeMillis() - start)); } /** * This one is faster when the excluded list is big */ private static List testLists2(List animals, List excluded) { List result = new ArrayList(); HashMap animalMap = new HashMap(); HashMap exclMap = new HashMap(); for (ProcessAnimal animal : animals) { animalMap.put(animal.getInternalId(), animal); } for (ProcessAnimal animal : excluded) { exclMap.put(animal.getInternalId(), animal); } Set keys = animalMap.keySet(); for (Integer key : keys) { if(exclMap.get(key) == null) { result.add(animalMap.get(key)); } } return result; } /** * This one is faster when the excluded list is small */ private static List testLists1(List animals, List excluded) { List result = new ArrayList(); for (ProcessAnimal animal : animals) { boolean included = true; for (ProcessAnimal excludedAnimal: excluded) { if(animal.getInternalId() == excludedAnimal.getInternalId()) { included = false; } } if(included) { result.add(animal); } } return result; }