从两个字符串数组返回公共元素的最有效方法

2022-01-25 00:00:00 arrays compare java

在 Java 中,从两个字符串数组返回公共元素的最有效方法是什么?我可以用一对 for 循环来做到这一点,但这似乎不是很有效.根据我对 List,然后应用 retainAllquestions/1235033/java-comparing-two-string-arrays-and-removing-elements-that-exist-in-both-array">类似的SO问题:

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);

推荐答案

这是一个单行:

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

retainAll impl(在 AbstractCollection 中)迭代 this,并在参数上使用 contains().将参数转换为 HashSet 将导致快速查找,因此 retainAll 内的循环将尽快执行.

The retainAll impl (in AbstractCollection) iterates over this, and uses contains() on the argument. Turning the argument into a HashSet will result in fast lookups, so the loop within the retainAll will execute as quickly as possible.

此外,名称 baseList 暗示它是一个常量,因此如果您缓存它,您将获得显着的性能提升:

Also, the name baseList hints at it being a constant, so you will get a significant performance improvement if you cache this:

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 preserve the original List, do this:

static List<String> retainCommonWithBase(List<String> strings) {
   List<String> result = new ArrayList<String>(strings);
   result.retainAll(BASE);
   return result;
}

相关文章