RobinUS2
RobinUS2

Reputation: 955

Fastest way to get arraylist items in all other arraylists

I'm looking for a smart and fast way of getting only the values, of multiple arraylists (stored in a hashmap), that are in ALL of the other arraylists.

E.g. [a] = 1, 2, 3, 4, 5 [b] = 1, 3 [c] = 3

Result = 3

What is the fastest way to achieve this in Java?

Upvotes: 0

Views: 685

Answers (3)

sjr
sjr

Reputation: 9885

In Google Guava:

  // assuming you have List<List<?>> lists that is non-empty
  Set<?> result = Sets.newLinkedHashSet(lists.get(0));
  for (int i = 1; i < lists.size(); i++) {
    result.retainAll(ImmutableSet.copyOf(lists.get(i)));
  }

  return result;

Upvotes: 3

Reimeus
Reimeus

Reputation: 159844

You can use Collections.retainAll using the ArrayLists:

list1.retainAll(list2);
list1.retainAll(list3);

but do bear in mind that you will change the content of list1.

Upvotes: 5

Alex Coleman
Alex Coleman

Reputation: 7326

Iterate through them, and add any identical ones to a new arraylist.

    List commons = new ArrayList();
    for(int i=0; i < list1.size() && i < list2.size(); i++) {
        Object list1val = list1.get(i);
        Object list2val = list2.get(i);
        if((list1val == null && list2val == null) ||
                (list1val != null && list1val.equals(list2val)))
                commons.add(list1val);
    }
}

Upvotes: 0

Related Questions