java8 list转换对象_Java8将List对象转换Map

基于Java8的函数式编程概念,去实现List转换Map

public class DemoMian2 {

public static void main(String[] args) {

List usersList = new ArrayList();

Users users = new Users();

users.setId(1L);

users.setName("张三");

users.setSex("男");

users.setCity("深圳");

usersList.add(users);

Users users2 = new Users();

users2.setId(2L);

users2.setName("张三");

users2.setSex("男");

users2.setCity("上海");

usersList.add(users2);

Users users3 = new Users();

users3.setId(3L);

users3.setName("张三");

users3.setSex("男");

users3.setCity("深圳");

usersList.add(users3);

Users users4 = new Users();

users4.setId(4L);

users4.setName("张三");

users4.setSex("男");

users4.setCity("上海");

usersList.add(users4);

Map collect = usersList.stream().collect(Collectors.toMap(Users::getId, Users -> Users));

collect.forEach((key, value) -> System.out.println(key + "-" + value));

}

}

/*

1-Users{id=1, name='张三', sex='男', city='深圳'}

2-Users{id=2, name='张三', sex='男', city='上海'}

3-Users{id=3, name='张三', sex='男', city='深圳'}

4-Users{id=4, name='张三', sex='男', city='上海'}

*/

注意:需要转换的key不能重复,如果出现重复的话,会报错已存在key

Exception in thread "main" java.lang.IllegalStateException: Duplicate key

Users{id=3, name='张三', sex='男', city='深圳'}

处理重复key可以使用如下模式:

package com.mars;

import java.util.*;

import java.util.function.Function;

import java.util.stream.Collectors;

/**

* TODO

*

* @Author: Yizq

* @Date: 2020/10/27 1:49 下午

*/

public class DemoMian2 {

public static void main(String[] args) {

List usersList = new ArrayList();

Users users = new Users();

users.setId(1L);

users.setName("张三");

users.setSex("男");

users.setCity("深圳");

usersList.add(users);

Users users2 = new Users();

users2.setId(2L);

users2.setName("张三");

users2.setSex("男");

users2.setCity("上海");

usersList.add(users2);

Users users3 = new Users();

users3.setId(3L);

users3.setName("张三");

users3.setSex("男1");

users3.setCity("深圳");

usersList.add(users3);

Users users4 = new Users();

users4.setId(3L);

users4.setName("张三");

users4.setSex("男2");

users4.setCity("上海");

usersList.add(users4);

Map collect = usersList.stream().collect(Collectors.toMap(Users::getId, Function.identity(), (key1, key2) -> key2));

collect.forEach((key, value) -> System.out.println(key + "-" + value));

}

}

/*

1-Users{id=1, name='张三', sex='男', city='深圳'}

2-Users{id=2, name='张三', sex='男', city='上海'}

3-Users{id=3, name='张三', sex='男2', city='上海'}

*/

使用这种方式,在处理过程中会将存在的key进行覆盖

标签:Map,Users,usersList,张三,List,users4,users2,users3,Java8

来源: https://www.cnblogs.com/xianbeier/p/14068382.html

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页