JDK8之Collectors之分组

1、建立一个实体类
public class Person {
private String color;
private Integer grice;

public Person() {
}

public Person(String color, Integer grice) {
this.color = color;
this.grice = grice;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public Integer getGrice() {
return grice;
}

public void setGrice(Integer wight) {
this.grice = wight;
}

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

2、测试一
List<Person> lists = Arrays.asList(
new Person("白色",1),
new Person("白色",2),
new Person("红色",3),
new Person("红色",4),
new Person("黑色",5)
);
(1)获取白色数据
List<Person> griceList = lists.stream().filter(t -> t.color.equals("白色")).collect(Collectors.toList());
(2)根据颜色进行分组
Map<String,List<Person>> groupMap = lists.stream().collect(Collectors.groupingBy(Person::getColor));
System.out.println("griceList ="+griceList.toString());
System.out.println("groupMap ="+groupMap.toString());



posted @ 2022-01-06 14:05  java_my_skill  阅读(347)  评论(0)    收藏  举报