Most efficient way to return common elements from two string arrays(从两个字符串数组返回公共元素的最有效方法)
问题描述
在 Java 中,从两个字符串数组返回公共元素的最有效方法是什么?我可以用一对 for 循环来做到这一点,但这似乎不是很有效.根据我对 List,然后应用 retainAll
questions/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;
}
这篇关于从两个字符串数组返回公共元素的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从两个字符串数组返回公共元素的最有效方法
基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01