有没有更好的方法在Java中组合两个字符串集? [英] Is there a better way to combine two string sets in java?
本文介绍了有没有更好的方法在Java中组合两个字符串集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要组合两个字符串集,同时过滤掉多余的信息,这是我想出的解决方案,有人可以建议一种更好的方法吗?也许我忽略了内置的东西?谷歌没有运气.
Set< String>oldStringSet = getOldStringSet();设置< String>newStringSet = getNewStringSet();for(字符串currentString:oldStringSet){如果(!newStringSet.contains(currentString)){newStringSet.add(currentString);}}
解决方案
由于 Set
不包含重复的条目,因此可以通过以下方式将两者合并:
newStringSet.addAll(oldStringSet);
是否添加两次都没有关系,该集合将只包含一次元素...例如,不需要使用 contains
方法进行检查. >
I need to combine two string sets while filtering out redundant information, this is the solution I came up with, is there a better way that anyone can suggest? Perhaps something built in that I overlooked? Didn't have any luck with google.
Set<String> oldStringSet = getOldStringSet();
Set<String> newStringSet = getNewStringSet();
for(String currentString : oldStringSet)
{
if (!newStringSet.contains(currentString))
{
newStringSet.add(currentString);
}
}
解决方案
Since a Set
does not contain duplicate entries, you can therefore combine the two by:
newStringSet.addAll(oldStringSet);
It does not matter if you add things twice, the set will only contain the element once... e.g it's no need to check using contains
method.
这篇关于有没有更好的方法在Java中组合两个字符串集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文