两个集合{"a","b","c","d","e"},{"d","e","f","g","h"}合并成一个集合,并且去掉重复的
Set可以自动去重,所以使用Set直接添加数据就可以。
public static void main(String[] args) {
List<String> strList1 = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
List<String> strList2 = new ArrayList<>(Arrays.asList("d", "e", "f", "g", "h"));
// 创建set并将strList1集合数据赋给set
Set<String> set = new HashSet<>(strList1);
// 将strList2集合合并到set
for (String str : strList2) {
set.add(str);
}
System.out.println("合并后:" + set);
}
直接用Set就行了
//Set集合
public static void main(String[] args) {
String[] str1={"a","b","c","d","e"};
String[] str2={"d","e","f","g","h"};
Set set1 = new HashSet(Arrays.asList(str1));
Set set2 = new HashSet(Arrays.asList(str2));
Set set = new HashSet();
// 并集
set.addAll(set1);
set.addAll(set2);
System.out.println("并集" + set);
// 交集
set.clear();
set.addAll(set1);
set.retainAll(set2);
System.out.println("交集" + set);
// 差集
set.clear();
set.addAll(set1);
set.removeAll(set2);
System.out.println("差集" + set);
}
//List集合
public static void main(String[] args) {
String[] str1 = { "a", "b", "c", "d", "e" };
String[] str2 = { "d", "e", "f", "g", "h" };
ArrayList list1 = new ArrayList(Arrays.asList(str1));
ArrayList list2 = new ArrayList(Arrays.asList(str2));
ArrayList list = new ArrayList();
// 并集
list.addAll(list1);
for (int i = 0; i < list2.size(); i++) {
if (!list.contains(list2.get(i)))
list.add(list2.get(i));
}
System.out.println("并集" + list);
// 交集
list.clear();
for (int i = 0; i < list2.size(); i++) {
if (list1.contains(list2.get(i)))
list.add(list2.get(i));
}
System.out.println("交集" + list);
// 差集
list.clear();
for (int i = 0; i < list1.size(); i++) {
if (!list2.contains(list1.get(i)))
list.add(list1.get(i));
}
System.out.println("差集" + list);
}
import java.util.Arrays;
import java.util.HashSet;
/**
* @author yangbocsu
* @create 2022/06/18
* @projectName test1
*/
public class Solution {
public static void main(String[] args) {
//{"a","b","c","d","e"};//,{"d","e","f","g","h"}
HashSet<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c", "d", "e"));
HashSet<String> set2 = new HashSet<>(Arrays.asList("d", "e", "f", "g", "h"));
System.out.println("set1: "+set1);
System.out.println("set2: "+set2);
// 把set2 合并到set1
for(String i : set2){
// 如果set1中没有 i(set2中的元素),就加入到set1中
if (!set1.contains(i)){
set1.add(i);
}
}
System.out.println("合并后:"+set1);
}
}