有没有更好的方法在java中组合两个字符串集?
我需要合并两个字符串集,同时过滤掉冗余信息,这是我提出的解决方案,有没有更好的方法可以推荐?也许是我忽略的内在因素?没有任何运气与谷歌
Set<String> oldStringSet = getOldStringSet();
Set<String> newStringSet = getNewStringSet();
for(String currentString : oldStringSet)
{
if (!newStringSet.contains(currentString))
{
newStringSet.add(currentString);
}
}
# 1 楼答案
与Guava相同:
# 2 楼答案
只需使用
newStringSet.addAll(oldStringSet)
。无需检查重复项,因为Set
实现已经这样做了# 3 楼答案
如果您使用的是番石榴,您也可以使用生成器来获得更大的灵活性:
# 4 楼答案
由于
Set
不包含重复条目,因此可以通过以下方式将两者结合起来:添加两次并不重要,集合只包含一次元素。。。e、 g不需要使用
contains
方法进行检查# 5 楼答案
定义集中的元素仅包含唯一的元素
为了增强代码,您可以为此创建一个通用方法
# 6 楼答案
你可以用这一行
通过静态导入,它看起来更漂亮
另一种方法是使用flatMap方法:
此外,任何集合都可以轻松地与单个元素组合