java list 并集
使用apache的CollectionUtils工具类
String[] arrayA = new String[] { "1", "2", "3", "4"};
String[] arrayB = new String[] { "3", "4", "5", "6" };
List<String> listA = Arrays.asList(arrayA);
List<String> listB = Arrays.asList(arrayB);
//1、并集 union
System.out.println(CollectionUtils.union(listA, listB));
//输出: [1, 2, 3, 4, 5, 6]
对象集合交、并、差处理
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
/**
* 为什么重写equals方法一定要重写hashCode方法下面也会讲
*/
@Override
public int hashCode() {
String result = name + age;
return result.hashCode();
}
/**
* 重写 equals 方法 根据name和age都相同那么对象就默认相同
*/
@Override
public boolean equals(Object obj) {
Person u = (Person) obj;
return this.name.equals(u.name) && (this.age.equals(u.age));
}
/**
* 重写 toString 方法
*/
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
List<Person> personList = new ArrayList<Person>();
Person person1 = new Person("小小",3);
Person person2 = new Person("中中",4);
personList.add(person1);
personList.add(person2);
List<Person> person1List = new ArrayList<Person>();
Person person3 = new Person("中中",4);
Person person4 = new Person("大大",5);
person1List.add(person3);
person1List.add(person4);
/**
* 1、差集
*/
System.out.println(CollectionUtils.subtract(personList, person1List));
//输出:[Person{name='小小', age=3}]
/**
* 2、并集
*/
System.out.println(CollectionUtils.union(personList, person1List));
//输出:[Person{name='小小', age=3}, Person{name='中中', age=4}, Person{name='大大', age=5}]
/**
* 3、交集
*/
System.out.println(CollectionUtils.intersection(personList, person1List));
//输出:[Person{name='中中', age=4}]
/**
* 4、交集的补集(析取)
*/
System.out.println(CollectionUtils.disjunction(personList, person1List));
//输出:[Person{name='小小', age=3}, Person{name='大大', age=5}]
}
}
参考:
https://www.cnblogs.com/ooo0/p/13091760.html