大家好,又见面了,我是你们的朋友全栈君。
基于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
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/145620.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...