Stream流groupingby分组获取每个分组第一条数据


原文链接:https://blog.csdn.net/weixin_42605307/article/details/124975561

public class StreamSkill {

    public static void main(String[] args) {
        List list = new ArrayList<>();
        TestData.TestDataBuilder builder = TestData.builder();
        builder.id(1).name("老王").age(50).address("隔壁");
        list.add(builder.build());
        builder.id(2).name("司马老贼").age(45).address("许昌");
        list.add(builder.build());
        builder.id(3).name("曹贼").age(43).address("许昌");
        list.add(builder.build());
        builder.id(4).name("大耳朵").age(52).address("益州");
        list.add(builder.build());
        builder.id(5).name("燕人").age(58).address("益州");
        list.add(builder.build());

        System.out.println(list);

        Map map = list.stream().collect(
                Collectors.groupingBy(TestData::getAddress, Collectors.collectingAndThen(
                        Collectors.reducing((t1, t2) -> t1.getAge() > t2.getAge() ? t1 : t2),
                        Optional::get
                ))
        );

        System.out.println(map);
    }
}


@Data
@Builder
class TestData{
    private Integer id;
    private String name;
    private Integer age;
    private String address;
}

你可能感兴趣的:(java,jvm,servlet)