天天看点

java8 stream 分组_java8 stream groupingBy 数据流分组

概述,使用java8的 stream groupingBy ,实现对list中的数据按照年龄对person对象的分组

1.Person

package com.qimh.springbootfiledemo;

public class Person {

private Integer age;

private String name;

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return "Person{" +

"age=" + age +

", name='" + name + '\'' +

'}';

}

}

2.测试方法

package com.qimh.springbootfiledemo;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;

public class MainTest {

public static void testStreamCollect(){

List persons = new ArrayList<>();//Arrays.asList();

Person person = new Person();

person.setAge(20);

person.setName("张三");

Person person2 = new Person();

person2.setAge(20);

person2.setName("李四");

Person person3 = new Person();

person3.setAge(20);

person3.setName("王五");

persons.add(person);

persons.add(person2);

persons.add(person3);

Person person4 = new Person();

person4.setAge(21);

person4.setName("王八");

persons.add(person4);

Map> callRecordMap = persons.stream().collect(Collectors.groupingBy(Person::getAge));

for (Map.Entry> entry:callRecordMap.entrySet()){

Integer age = entry.getKey();

List personss = entry.getValue();

System.out.println("age:"+age);

System.out.println("personss:"+personss);

}

}

public static void main(String[] args){

testStreamCollect();

}

}

3.结果

age:20

personss:[Person{age=20, name='张三'}, Person{age=20, name='李四'}, Person{age=20, name='王五'}]

age:21

personss:[Person{age=21, name='王八'}]

参考连接:

https://cloud.tencent.com/developer/article/1187833 (下)

对流知识补充的连接:

https://cloud.tencent.com/developer/article/1187831 (上)