Java – the most efficient way to return common elements from two string arrays

In Java, what is the most effective way to return common elements from two string arrays? I can do it with a pair of for loops, but it doesn't seem to be very effective According to my comments on similar so question, the best way I can think of is to convert it to a list and then apply retainAll

List<String> compareList = Arrays.asList(strArr1);
List<String> baseList = Arrays.asList(strArr2);
baseList.retainAll(compareList);

Solution

Edit:

This is a single line:

compareList.retainAll(new HashSet<String>(baseList));

RetainAll impl (in abstractcollection) iterates through the loop and uses contains () on the parameter Converting a parameter to a HashSet will result in a fast lookup, so the loop in retain all will execute as quickly as possible

In addition, the name of baselist indicates that it is a constant, so if you cache this function, you will get a significant performance improvement:

static final Set<String> BASE = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("one","two","three","etc")));

static void retainCommonWithBase(Collection<String> strings) {
    strings.retainAll(BASE);
}

If you want to keep the original list:

static List<String> retainCommonWithBase(List<String> strings) {
   List<String> result = new ArrayList<String>(strings);
   result.retainAll(BASE);
   return result;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>