从两个字符串数组返回公共元素的最有效方法 [英] Most efficient way to return common elements from two string arrays

查看:13
本文介绍了从两个字符串数组返回公共元素的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,从两个字符串数组返回公共元素的最有效方法是什么?我可以用一对 for 循环来做到这一点,但这似乎不是很有效.根据我对 类似的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;
}

这篇关于从两个字符串数组返回公共元素的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆