1、多属性合并
根据stream中对象的多个相同属性对不同的属性进行合并/聚合
//比如我们需要根据 相同的年龄 性别 ,把名字拼接起来(或者是别的操作)
List<User> list = new ArrayList();
User user1 = new User1();
user1.name = "张三";
user1.sex = "男";
user1.age = 18;
User user2 = new User1();
user3.name = "李四";
user1.sex = "男";
user3.age = 18;
list.add(user1); list.add(user2);
Map<String, User> sexAndAge = list.stream().collect(Collectors.toMap(item ->
item.getName + "-" + item.getSex() , vo -> vo, (v1,v2)-> {
v1.getname() + "-" + v2.getname();
return v1;
}) );
2、根据多字段去重
List<user> infoList = new ArrayList<>();
//实体类 orderNumber userName age
infoList.add(new user("1", "xc", "22"));
infoList.add(new user("1", "xc", "33"));
infoList.add(new user("2", "xc", "23"));
infoList.add(new user("2", "xc", "33"));
infoList.add(new user("2", "xy", "22"));
List<user> list = infoList.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(f -> f.getUserName() + "-" + f.getOrderNumber()))), ArrayList::new));
System.out.println(list);
3、根据多字段获取重复数据
List<user> infoList = new ArrayList<>();
//实体类 orderNumber userName age
infoList.add(new user("1", "xc", "22"));
infoList.add(new user("1", "xc", "33"));
infoList.add(new user("2", "xc", "23"));
infoList.add(new user("2", "xc", "33"));
infoList.add(new user("2", "xy", "22"));
List<user> list = infoList.stream().
.collect(Collectors.groupingBy(person -> person.getUserName() + "_" + person.getOrderNumber()+ "_"))
.values().stream().filter(list -> list.size() >1).map(list -> list.get(0)).collect(Collectors.toList());
System.out.println(list);