java8 list转map

//按id属性为map的key值
Map<Integer, User> userMap = list.stream().collect(Collectors.toMap(User::getId, user -> user));

注意:这里属性值必须不能重复,不然会报错

举例:

public class HelloWorld {

    public static void main(String[] args) {
        Random random = new Random();
        List<User> list = new ArrayList<>();
        for(int i=1;i<=10;i++) {
            String group = (random.nextInt(3) + 1) + "组";//1-3组随机
            User u = new User(i, "用户-" + i, group);
            list.add(u);
        }

        //按id属性分组
        Map<Integer, User> userMap = list.stream().collect(Collectors.toMap(User::getId, user -> user));

        System.out.println("list-map 后:" + userMap);
    }
    private static class User{
        Integer id;
        String name;
        String group;

        public User(Integer id, String name, String group) {
            this.id = id;
            this.name = name;
            this.group = group;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getGroup() {
            return group;
        }

        public void setGroup(String group) {
            this.group = group;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", group='" + group + '\'' +
                    '}';
        }
    }

}

执行结果:

list-map 后:{
  1=User{
    id=1,
    name='用户-1',
    group='1组'
  },
  2=User{
    id=2,
    name='用户-2',
    group='3组'
  },
  3=User{
    id=3,
    name='用户-3',
    group='3组'
  },
  4=User{
    id=4,
    name='用户-4',
    group='3组'
  },
  5=User{
    id=5,
    name='用户-5',
    group='3组'
  },
  6=User{
    id=6,
    name='用户-6',
    group='3组'
  },
  7=User{
    id=7,
    name='用户-7',
    group='1组'
  },
  8=User{
    id=8,
    name='用户-8',
    group='2组'
  },
  9=User{
    id=9,
    name='用户-9',
    group='1组'
  },
  10=User{
    id=10,
    name='用户-10',
    group='1组'
  }
}

 

posted @ 2018-01-29 15:54  艺言弈行  阅读(367)  评论(0编辑  收藏  举报