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


    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM