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、求最大值和最小值


    }
}
posted @ 2020-01-11 10:46  薛柏梁  阅读(2205)  评论(0编辑  收藏  举报