• 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、求最大值和最小值
    
    
        }
    }
  • 相关阅读:
    Python基础实例001:数字组合问题
    Python集合
    标量、向量、矩阵、张量
    re模块函数之search
    Python常用字符串操作
    Python基础之元组
    Bai, IEEE 2019
    词嵌入
    RNN 训练时梯度爆炸和梯度消失的理解
    OCR 综述
  • 原文地址:https://www.cnblogs.com/BonnieWss/p/10070062.html
Copyright © 2020-2023  润新知