java8快速实现分组过滤list转map
Posted 薛柏梁
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java8快速实现分组过滤list转map相关的知识,希望对你有一定的参考价值。
public class TestEntity { private String c1; private String c2; public TestEntity(){} public TestEntity(String a,String b){ this.c1=a; this.c2=b; } public String getC1() { return c1; } public void setC1(String c1) { this.c1 = c1; } public String getC2() { return c2; } public void setC2(String c2) { this.c2 = c2; } public String toString(){ return "TestEntity{c1="+c1+","+"c2="+c2+"}"; } }
public class java8Test { public static void main(String[] args){ TestEntity t1=new TestEntity("a","1"); TestEntity t2=new TestEntity("a","2"); TestEntity t3=new TestEntity("b","3"); List<TestEntity> list=new ArrayList<>(); list.add(t1); list.add(t2); list.add(t3); //1、分组 Map<String,List<TestEntity>> map=list.stream().collect(Collectors.groupingBy(TestEntity::getC1));//按照c1分组 System.out.println(map); //{a=[TestEntity{c1=a,c2=1}, TestEntity{c1=a,c2=2}], b=[TestEntity{c1=b,c2=3}]} //2、List转Map //如果有重复的key,则保留k1,舍弃k2。可以用(k1,k2)->k1来设置 Map<String,TestEntity> map1=list.stream().collect(Collectors.toMap(TestEntity::getC1,a->a,(k1,k2)->k1)); System.out.println(map1); //{a=TestEntity{c1=a,c2=1}, b=TestEntity{c1=b,c2=3}} //3、过滤Filter List<TestEntity> list1=list.stream().filter(a->a.getC1().equals("a")).collect(Collectors.toList()); System.out.println(list1); //[TestEntity{c1=a,c2=1}, TestEntity{c1=a,c2=2}] //4、求和 //5、求最大值和最小值 } }
以上是关于java8快速实现分组过滤list转map的主要内容,如果未能解决你的问题,请参考以下文章
Java8 Stream针对List先分组再求和最大值最小值平均值等