如何创建一个新的哈希集来组合其他两个集的公共字符串值(区分大小写)?
主要方法包括:
public static void main(String[] args) {
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.add("blue");
set1.add("red");
set1.add("yellow");
set2.add("blue");
set2.add("red");
set2.add("orange");
}
方法标题为:
public static Set<String> buildList (Set<String>set1, Set<String>set2){
set<String> set3 = new HasSet<String>();
}
如果我正确理解你的问题,那么你需要保留两个HashSet
的共同值如果是,那么使用set1.retainAll(set2)
代码:
public static void main(String[] args) {
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.add("blue");
set1.add("red");
set1.add("yellow");
set2.add("blue");
set2.add("red");
set2.add("orange");
set1.retainAll(set2);
System.out.println(set1);
}
输出:
[red, blue]
您可以修改buildList方法,如下所述,它将返回字符串的公共列表作为结果。
public static Set<String> buildList (Set<String>set1, Set<String>set2){
set1.retainAll(set2);
return set1;
}