利用java8分组并根据某个字段取最大的一条数据
返回是个map ,map的key是分组的字段。
·
测试例子如下:
返回是个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());
结果:
更多推荐
已为社区贡献2条内容
所有评论(0)