java流对List中(一个或多个)相同属性的实体合并

package Test;

import entity.Person;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: X22020
 * @Date: 2022/11/25/16:23
 * @Description:
 */
public class ListTest {
          
   
    public static void main(String[] args) {
          
   
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Tom", 7000, 23, "male", "Washington"));
        personList.add(new Person("Tom", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        personList.add(new Person("Alisa", 9500, 26, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

        //根据一个属性合并
        List<Person> result = personList.stream()
                .collect(Collectors.toMap(Person::getName,a -> a, (o1, o2) -> {
          
   
                    o1.setSalary(o1.getSalary() + o2.getSalary());
                    return o1;
                })).values().stream().collect(Collectors.toList());
        System.out.println(result);
在这里插入图片描述

        //根据两个属性合并
        List<Person> list = new ArrayList<>();
        personList.parallelStream().collect(Collectors.groupingBy(o->(o.getName() + o.getAge()),Collectors.toList()))
                .forEach((id,transfer) -> {
          
   
            transfer.stream().reduce((a,b) ->new Person(a.getName(),a.getSalary() + b.getSalary(),a.getAge(),a.getSex(),a.getArea()))
                    .ifPresent(list::add);
        });

        list.forEach(System.out::println);

        }
    }
经验分享 程序员 微信小程序 职场和发展