码迷,mamicode.com
首页 > 其他好文 > 详细

Lamda groupingBy

时间:2020-06-07 11:14:22      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:key   entry   amd   static   get   oid   each   字段   foreach   


package com.fql.lamda.Lamda;


import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import javax.swing.plaf.synth.SynthSeparatorUI;


import com.fql.entity.Foo;


/*
*Collectors.groupingBy(a,Function)
* a:被groupby的字段; fucntion:聚合后得到结果,比如fucntion是Collectors.toList()是聚合后转为list,是Collectors.counting是聚合后count值
*
*/


public class LamdaGroupBy {
public static void main(String[] args) {
List<Foo> fooList = Arrays.asList(
new Foo("A","san",99.0,2),
new Foo("A","nas",613.0,1),
new Foo("B","san",112.0,3),
new Foo("C","san",43.0,5),
new Foo("B","nas",77.0,7)
);
//1. groupby(a,Collectors.toList()) 聚合后转化为Map<Object,List<>)
Map<Object,List<Foo>>listMap=fooList.stream().collect(Collectors.groupingBy(f->f.getName(),Collectors.toList()));
listMap.entrySet().forEach(lk->{
List<Foo> listT=lk.getValue();
listT.sort((l1,l2)->l1.getScore().compareTo(l2.getScore()));  //将每个key对应valueList内容按照score进行排序
System.out.println("mapList_Name:"+lk.getValue().get(0).getName()+"mapList_score:"+lk.getValue().get(0).getScore());
});
System.out.println("end 1...");
//2.
Map<String,Long> mapCount=fooList.stream().collect(Collectors.groupingBy(f->f.getGrade(),Collectors.counting()));
mapCount.entrySet().stream().forEach(m->{
System.out.println("key:"+m.getKey());
System.out.println("value:"+m.getValue());
});
System.out.println("end 2...");
}


}

 

运行结果:

mapList_Name:nas mapList_score:77.0
mapList_Name:san mapList_score:43.0
end 1...
key:A
value:2
key:B
value:2
key:C
value:1
end 2...

Lamda groupingBy

标签:key   entry   amd   static   get   oid   each   字段   foreach   

原文地址:https://www.cnblogs.com/enhance/p/13059006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!