测试例子如下:

返回是个map ,map的key是分组的字段 

       TestObj testObj1 = new TestObj();
        testObj1.setJob("ceshi1");
        testObj1.setNum(4);
        TestObj testObj2 = new TestObj();
        testObj2.setJob("ceshi1");
        testObj2.setNum(2);
        TestObj testObj3 = new TestObj();
        testObj3.setJob("ceshi1");
        testObj3.setNum(1);
        TestObj testObj4 = new TestObj();
        testObj4.setJob("ceshi2");
        testObj4.setNum(2);
        TestObj testObj5 = new TestObj();
        testObj5.setJob("ceshi2");
        testObj5.setNum(1);
        List<TestObj> list = new ArrayList<>();
        list.add(testObj1);
        list.add(testObj2);
        list.add(testObj3);
        list.add(testObj4);
        list.add(testObj5);
        Map<String, TestObj> maxAgePerson =list.stream()
                .collect(Collectors.groupingBy(TestObj::getJob,
                        Collectors.collectingAndThen(
                                Collectors.maxBy(Comparator.comparingInt(TestObj::getNum)),
                                Optional::get)));
        System.out.println(maxAgePerson.toString());

结果:

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐