zoukankan      html  css  js  c++  java
  • 【java/Lamda】List.stream().collect(Collectors.toMap(Emp::getId, a->a,(k1,k2)->k2))的意义

    List.stream().collect(Collectors.toMap(Emp::getId, a->a,(k1,k2)->k2))的意义是:将链表里的元素转成Map,Map的键取元素的id,值就取元素本身,当键同值不同时取后来者。

    例程:

    Emp类:

    public class Emp {
        private String id;
        private String name;
        
        public Emp(String id,String name) {
            this.id=id;
            this.name=name;
        }
        
        public String toString() {
            return this.id+"/"+this.name;
        }
        
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    程序:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class Test2 {
        public static void main(String[] args) {
            List<Emp> emps=new ArrayList<>();
            emps.add(new Emp("1","Andy"));
            emps.add(new Emp("2","Bill"));
            emps.add(new Emp("3","Cindy"));
            emps.add(new Emp("4","Douglas"));
            emps.add(new Emp("4","Eliot"));
            
            //Emp::getId Map的key取元素的id 
            //a->a Map的值取整体
            //(k1,k2)->k2) 两键相同值不同时时取后来的值
            Map<String,Object> map=emps.stream().collect(Collectors.toMap(Emp::getId, a->a,(k1,k2)->k2));
            
            for(String key:map.keySet()) {
                System.out.println(key+":"+map.get(key));
            }
        }
    }

    输出:

    1:1/Andy
    2:2/Bill
    3:3/Cindy
    4:4/Eliot

    参考资料:

    https://zhangzw.com/posts/20191205.html

  • 相关阅读:
    C指针
    redis五种基本数据类型
    mongoDB MapReduce
    JSON传参
    mongodb查询实练
    逻辑数据结构和存储数据结构
    线性表的顺序存储和链式存储
    数据结构和算法关系
    UIActivityIndicatorView使用
    Swift中格式化日期
  • 原文地址:https://www.cnblogs.com/heyang78/p/15327662.html
Copyright © 2011-2022 走看看