java8 List转Map,并进行分组过滤求和等操作

定义实体类:

public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试:

public static void main(String[] args) {
        List<Person> personList = Lists.newArrayList();
        Person p1 = new Person("Liu",30);
        Person p2 = new Person("Yu",23);
        Person p3 = new Person("Liu",27);

        personList.add(p1);
        personList.add(p2);
        personList.add(p3);
        Map<String,Person> personMap1 = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity(),(k1,k2)->k2));
        //{Liu=Person{name='Liu', age=27}, Yu=Person{name='Yu', age=23}}
        System.out.println(personMap1);
        //等价于上面
        Map<String,Person> personMap2 = personList.stream().collect(Collectors.toMap(Person::getName,p->p,(k1,k2)->k2));
        //{Liu=Person{name='Liu', age=27}, Yu=Person{name='Yu', age=23}}
        System.out.println(personMap2);
        //分组,将相同的key值放到List
        Map<String,List<Person>> personMap3 = personList.stream().collect(Collectors.groupingBy(Person::getName));
        //{Liu=[Person{name='Liu', age=30}, Person{name='Liu', age=27}], Yu=[Person{name='Yu', age=23}]}
        System.out.println(personMap3);
        //过滤
        List<Person> filterList  = personList.stream().filter(p -> p.getName().equals("Liu")).collect(Collectors.toList());
        //[Person{name='Liu', age=30}, Person{name='Liu', age=27}]
        System.out.println(filterList);
        //求和
        Integer totalAge = personList.stream().mapToInt(Person::getAge).sum();
        //80
        System.out.println(totalAge);
    }
原创文章 317 获赞 416 访问量 112万+

猜你喜欢

转载自blog.csdn.net/u014082714/article/details/102465462