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

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

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

这是单线的:

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

retainAll
IMPL(类AbstractCollection中)遍历
this
,以及用途
contains()
的说法。将参数转换为a
HashSet
将导致快速查找,因此a中的循环
retainAll
将尽快执行

另外,名称

baseList
暗示它是一个常量,因此,如果缓存以下内容,将会获得显着的性能改进:

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

如果要保留原始列表,请执行以下 *** 作:

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5501237.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存