List对象 交集 并集 差集 及 判断属性多值 相同不同


List<StudentDTO> oldList = Arrays.asList(
new StudentDTO(111, "aaa", 16, "123@163", "123"),
new StudentDTO(222, "bbb", 18, "123@163", "456"),
new StudentDTO(666, "fff", 20, "123@163", "999")
);

List<StudentDTO> newList = Arrays.asList(
new StudentDTO(111, "aaa", 16, "123@163", "123"),
new StudentDTO(222, "bbb", 18, "123@163", "456"),
new StudentDTO(333, "ccc", 19, "123@163", "789")
);

@Test
public void test() {
//根据名字交集 111 222
List<StudentDTO> andList = newList.stream()
.filter(item -> oldList.stream()
.map(e -> e.getName()).collect(Collectors.toList()).contains(item.getName()))
.collect(Collectors.toList());

System.out.println(andList);
}
@Test
public void test2() {
//差集oldList-oldList 666
List<StudentDTO> list = oldList.stream()
.filter(item -> !newList.stream().map(e -> e.getName()).collect(Collectors.toList()).contains(item.getName()))
.collect(Collectors.toList());

System.out.println(list);
}
@Test
public void test3() {
//差集newList-oldList 333
List<StudentDTO> list = newList.stream()
.filter(item -> !oldList.stream().map(e -> e.getName()).collect(Collectors.toList()).contains(item.getName()))
.collect(Collectors.toList());

System.out.println(list);
}
@Test
public void test4() {
//差集newList-oldList基础上 判断 id name 都不相同
List<StudentDTO> list = newList.stream()
.filter(item -> !oldList.stream().map(e -> e.getId() + "&" + e.getName())
.collect(Collectors.toList()).contains(item.getId() + "&" + item.getName())
).collect(Collectors.toList());

System.out.println(list);
}
@Test
public void test5() {
//id相同 name不同
List<StudentDTO> list = newList.stream()
.filter(item -> oldList.stream().map(e -> e.getId())
.collect(Collectors.toList()).contains(item.getId()))
.filter(item -> !oldList.stream().map(e -> e.getName())
.collect(Collectors.toList()).contains(item.getName()))
.collect(Collectors.toList());

System.out.println(list);
}

/**
* 导入jar
* <dependency>
* <groupId>org.apache.commons</groupId>
* <artifactId>commons-collections4</artifactId>
* <version>4.1</version>
* </dependency>
*/

@Test
public void test6() {
//获取两个集合交集的补集 即 newList + oldList - 交集
Collection<StudentDTO> disjunction = CollectionUtils.disjunction(newList, oldList);
System.out.println("补集" + disjunction);
//获取两个集合并集(自动去重)
Collection<StudentDTO> union = CollectionUtils.union(newList, oldList);
System.out.println("并集" + union);
//交集
Collection<StudentDTO> intersection = CollectionUtils.intersection(newList, oldList);
System.out.println("交集" + intersection);
//获取两个集合的差集 交集 - oldList
Collection<StudentDTO> subtract = CollectionUtils.subtract(newList, oldList);
System.out.println("oldList差集"+subtract);
//获取两个集合的差集 交集 -newList
Collection<StudentDTO> subtract2 = CollectionUtils.subtract(oldList,newList);
System.out.println("newList差集"+subtract2);
}
古人学问无遗力,少壮工夫老始成。 纸上得来终觉浅,绝知此事要躬行。
原文地址:https://www.cnblogs.com/wf-zhang/p/13574925.html