In Java, what’s the most efficient way to return the common elements from two String Arrays? I can do it with a pair of for loops, but that doesn’t seem to be very efficient. The best I could come up with was converting to a List and then applying retainAll, based on my review of a similar SO question:
List<String> compareList = Arrays.asList(strArr1);
List<String> baseList = Arrays.asList(strArr2);
baseList.retainAll(compareList);
EDITED:
This is a one-liner:
The
retainAllimpl (in AbstractCollection) iterates overthis, and usescontains()on the argument. Turning the argument into aHashSetwill result in fast lookups, so the loop within theretainAllwill execute as quickly as possible.Also, the name
baseListhints at it being a constant, so you will get a significant performance improvement if you cache this:If you want to preserve the original List, do this: