提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
java8stream流式操作
一、常用交集并集
开发过程中常常操作两个list合并、差集、交集等等,根基某几个字段过滤。
二、使用步骤
1.新建DTO
代码如下(示例):
@Data
public class Account {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private Double money;
public Account(int id, String name, double money) {
this.id = id;
this.name = name;
this.money = money;
}
}
2.赋值list
代码如下(示例):
List<Account> list1 = new ArrayList<>();
List<Account> list2 = new ArrayList<>();
// 填充列表
list1.add(new Account(1, "A",20));
list1.add(new Account(2, "B",20));
list1.add(new Account(3, "C",201));
list2.add(new Account(2, "B",20));
list2.add(new Account(3, "C",20));
list2.add(new Account(4, "D",20));
3.差集
代码如下(示例):
List<Account> diff = list1.stream()
.filter(item -> list2.stream().noneMatch(other -> other.getId().equals(item.getId()) && StringUtils.equals(other.getName(),item.getName())))
.collect(Collectors.toList());
diff.forEach(item -> System.out.println("Id: " + item.getId() + ", Name: " + item.getName()));
4.交集
代码如下(示例):
// 取交集仅基于id和name属性
List<Account> intersectionDiff = list1.stream()
.filter(item1 -> list2.stream()
.anyMatch(item2 -> item2.getId().equals(item1.getId()) && item2.getName().equals(item1.getName())))
.collect(Collectors.toList());
intersectionDiff.forEach(item -> System.err.println("Id1: " + item.getId() + ", Name1: " + item.getName()));
总结
后续常用的还会补充