zoukankan      html  css  js  c++  java
  • Java8中list转map方法总结

    list转map在Java8中stream的应用
    1.利用Collectors.toMap方法进行转换

    public Map<Long, String> getIdNameMap(List<Account> accounts) {
        return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
    }

    其中第一个参数就是可以,第二个参数就是value的值。
    2.收集对象实体本身
    在开发过程中我们也需要有时候对自己的list中的实体按照其中的一个字段进行分组(比如 id ->List),这时候要设置map的value值是实体本身。

    public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
        return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
    }

    account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法 Function.identity(),这个方法返回自身对象,更加简洁
    重复key的情况。
    在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key。这时候就要在toMap方法中指定当key冲突时key的选择。(这里是选择第二个key覆盖第一个key)

    public Map<String, Account> getNameAccountMap(List<Account> accounts) {
        return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
    }

    用groupingBy 或者 partitioningBy进行分组
    根据一个字段或者属性分组也可以直接用groupingBy方法,很方便。

    Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).limit(100).collect(Collectors.groupingBy(Person::getAge));
    Iterator it = personGroups.entrySet().iterator();
    while (it.hasNext()) {
     Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();
     System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());
    }

    使用guava

     Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
                @Override
                public Long apply(User user) {
                    return user.getId();
                }
       });

    有时候,希望得到的map的值不是对象,而是对象的某个属性,那么可以用下面的方式:

    Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));
    郭慕荣博客园
  • 相关阅读:
    Ant-编译构建(2)-第3方jar包引入、log4j2
    Ant-编译构建(1)-HelloWorld
    java List的初始化
    传入json字符串的post请求
    HttPclient 以post方式发送json
    cron表达式详解,cron表达式写法,cron表达式例子
    深入理解SQL的四种连接-左外连接、右外连接、内连接、全连接
    Java两种延时——thread和timer
    List<List<Object>> list = new ArrayList<List<Object>>(); 求回答补充问题 list.get(position).add(Object);为什么会报错啊我想在对应的list里面添加对象
    关于 charset 的几种编码方式
  • 原文地址:https://www.cnblogs.com/jelly12345/p/15095209.html
Copyright © 2011-2022 走看看