import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.*;
import java.util.stream.Collectors;
public class ListGroupFindFirstTest3 {
public static void main(String[] args) {
List couponList = new ArrayList<>();
Person person1 = new Person(1,10000,"tom");
Person person2 = new Person(2,20000,"ketty");
Person person3 = new Person(3,30000,"jerry");
Person person4 = new Person(3,40000,"lilei");
couponList.add(person1);
couponList.add(person2);
couponList.add(person3);
couponList.add(person4);
//1 list分组筛选
Map> resultList1 = couponList.stream().collect(
Collectors.groupingBy(Person::getCardno));
//2 list筛选 取分组内的第一值
Map resultList =
couponList.stream().collect(
Collectors.groupingBy(Person::getCardno,
//包装后的收集器
Collectors.collectingAndThen(Collectors.toList(), value->value.get(0))));
//3 list筛选 取分组内根据条件筛选 price最高的一个
Map resultList2 =
couponList.stream().collect(
Collectors.groupingBy(Person::getCardno,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingInt(Person::getSalary)), Optional:: get))
);
//SerializerFeature.PrettyFormat JSON格式化输出
System.out.println(JSON.toJSONString(resultList2, SerializerFeature.PrettyFormat));;
}
}
class Person {
private Integer cardno;
private Integer salary;
private String name;
public Person(Integer cardno, Integer salary, String name) {
this.cardno = cardno;
this.salary = salary;
this.name = name;
}
public Integer getCardno() {
return cardno;
}
public void setCardno(Integer cardno) {
this.cardno = cardno;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}