Lamda groupingBy

Posted enhance

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lamda groupingBy相关的知识,希望对你有一定的参考价值。


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的主要内容,如果未能解决你的问题,请参考以下文章

Collectors.groupingBy分组后的排序问题

Collectors.groupingBy分组后的排序问题

Lamda Expression

Lamda表达式

Java 8中Collectors.groupingBy方法空指针异常源码分析

Lamda Expression