0

I'm trying to create a List<Object> aggregated based on List<Object> pool1 and List<Object> pool2. The main concern here is obviously performance since we have to compare every object in pool1 to every object in pool2. Is List necessary the best option?

Bad code version of the above:

List<Object> pool1 = new ArrayList<>();
List<Object> pool2 = new ArrayList<>();
List<Object> matchingObjects = new ArrayList<Object>();
for (Object p1 : pool1) {
    for (Object p2 : pool2) {
        if (p1.equals(p2)) {
            matchingObjects.add(p1);
        }
    }
}
Noobcanon
  • 3
  • 3

1 Answers1

0

retainAll will give a common elements between two lists

  pool1.retainAll(pool2);
  //pool1 contains elements common between two lists

if you want a saparate list of common elements than follow below process

List<Object> matchingObjects =  (ArrayList<Object>)pool1.clone();
matchingObjects.retainAll(pool2); // now matchingObjects will contain all the common elements
Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49