三种将list转换为map的方法
1) 传统方法
假设有某个类如下
Java代码
class Movie {
private Integer rank;
private String description;
public Movie(Integer rank, String description) {
super();
this.rank = rank;
this.description = description;
}
public Integer getRank() {
return rank;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("rank", rank)
.add("description", description)
.toString();
}
}
1、使用传统的方法:
public void convert_list_to_map_with_java () {
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map<Integer, Movie> mappedMovies = new HashMap<Integer, Movie>();
for (Movie movie : movies) {
mappedMovies.put(movie.getRank(), movie);
}
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
2、JAVA 8直接用流的方法
public void convert_list_to_map_with_java8_lambda () {
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map<Integer, Movie> mappedMovies = movies.stream().collect(
Collectors.toMap(Movie::getRank, (p) -> p));
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
(2)转换过程中的两个问题
a、key重复
重复时用后面的value 覆盖前面的value
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key2 ));
重复时将前面的value 和后面的value拼接起来
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));
重复时将重复key的数据组成集合
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));
b、valve为null
在转换流中加上判空,即便value为空,依旧输出
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
))
3、使用guava 工具类库
public void convert_list_to_map_with_guava () {
List<Movie> movies = Lists.newArrayList();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map<Integer,Movie> mappedMovies = Maps.uniqueIndex(movies, new Function <Movie,Integer> () {
public Integer apply(Movie from) {
return from.getRank();
}});
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------** 分隔符 **--------------------------------------------------------------------------------------------------------------------------------------------------------------------
一、
list转map
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
二、
另外,转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map的时候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
三、
有时候,希望得到的map的值不是对象,而是对象的某个属性,那么可以用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));
四、
//List 以ID分组 Map<Integer,List>
Map<Integer, List> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
System.err.println(“groupBy:”+groupBy);
{1=[Apple{id=1, name=‘苹果1’, money=3.25, num=10}, Apple{id=1, name=‘苹果2’, money=1.35, num=20}], 2=[Apple{id=2, name=‘香蕉’, money=2.89, num=30}], 3=[Apple{id=3, name=‘荔枝’, money=9.99, num=40}]}
三种将list转换为map的方法的更多相关文章
- 三种将list转换为map的方法(传统方法、jdk8 Stream流、guava)
三种将list转换为map的方法 - jackyrong - ITeye博客:http://jackyrong.iteye.com/blog/2158009
- [转]SQL三种获取自增长的ID方法
最新更新请访问: http://denghejun.github.io SQL SERVER中的三种获得自增长ID的方法 这个功能比较常用,所以记下来以防自己忘掉. SCOPE_IDENTIT ...
- 三种dedecms调用相关文章的方法
在文章的末尾或侧边栏添加相关文章可以提高用户的黏度,提高pv,增加se的好印象(哈哈),那么dedecms如何调用相关文章呢?有三种方法可以实现. 第一种dedecms调用相关文章的方法,用默认的li ...
- MySQL、SQLServer2000(及SQLServer2005)和ORCALE三种数据库实现分页查询的方法
在这里主要讲解一下MySQL.SQLServer2000(及SQLServer2005)和ORCALE三种数据库实现分页查询的方法. 可能会有人说这些网上都有,但我的主要目的是把这些知识通过我实际的应 ...
- 三种计算c#程序运行时间的方法
三种计算c#程序运行时间的方法 第一种: 利用 System.DateTime.Now // example1: System.DateTime.Now method DateTime dt1 = S ...
- Java中将对象转换为Map的方法
将对象转换为Map的方法,代码如下: /** * 将对象转成TreeMap,属性名为key,属性值为value * @param object 对象 * @return * @throws Illeg ...
- Win10计算器在哪里?三种可以打开Win10计算器的方法图文介绍
全新的windows10系统带来了不少新的特性和改变,其中win10的计算器位置就发生了很多的变化,导致很多网友们都以为win10计算器不见了,那么,win10计算器在哪里?如何打开?针对此问题,本文 ...
- 旧书重温:0day2【2】 实验:三种获取kernel32.dll基址的方法
0x01 找kernel32基地址的方法一般有三种: 暴力搜索法.异常处理链表搜索法.PEB法. 0x02 基本原理 暴力搜索法是最早的动态查找kernel32基地址的方法.它的原理是几乎所有的win ...
- 在Linux中三种让crontab每秒执行任务的方法
第一种方法: 1.创建脚本文件 cat phplog.sh 2.编辑脚本内容 #!/bin/bash while : ;do /home/scripts.sh 2>/dev/null & ...
- 三种找回 linux root密码的方法
找回 linux root密码的三种方法 第1种方法: 1.在系统进入单用户状态,直接用passwd root去更改2.用安装光盘引导系统,进行linux rescue状态,将原来/分区挂接上来,作法 ...
随机推荐
- maven-阿里云镜像
<mirror> <id>nexus-aliyun</id> <mirrorOf>*,!jeecg,!jeecg-snapshots&l ...
- Linux 中设置静态的IP
Topic (What i going to write) Setting the static Ip address in linux Main Information Firstly use CD ...
- AC和瘦AP组网
ac和瘦ap组网 参考了这篇文章[Cisco Packet Tracer]WLC配置瘦AP指南_时间进行的小宇的博客-CSDN博客_思科瘦ap配置命令 服务器server-pt配置 先设置IP地址,随 ...
- shell_Day04
grep程序 Linux下有文本处理三剑客 -- grep sed awk grep:文本 行过滤工具 sed: 文本 行编辑器(流编辑器) awk:报告生成器(做文本输出格式化) grep 包含三个 ...
- .什么是 SPA 单页面,它的优缺点分别是什么
SPA( single-page application )即一个web项目就只有一个页面(即一个HTML文件,HTML 内容的变换是利用路由机制实现的. 仅在 Web 页面初始化时加载相应的 HTM ...
- 前端之Vue day07 混入、插件、elementui、Router、Vuex
一.Props补充 1.父传子在子组件标签上起自定义属性 使用数组 就不演示了,太简单了 2.限制传入的数据类类型 使用对象 同样,展示过的 3.props补充 就是套对象,加以限制 props:{ ...
- python 操作 ES 一、基础操作
示例代码环境 python:3.8 es:7.8.0环境安装 pip install elasticsearch==7.8.0 from elasticsearch import Elasticsea ...
- npm vue-router安装报错
因为2022年2月7日以后,vue-router的默认版本,为4版本,而且 vue-router4,只能在vue3中,只有vue-router3中,能用在vue 2中 如果把vue-router4强制 ...
- 网络-6 IPV6(上)
一.iPv4与ipv6对比 1.ipv4与ipv6优缺点 1.1 Ipv4与ipv6对比,ipv4中的切片使用的三个字段:identification flags fragment offse ...
- 一周ppt 总结
最近写了一篇培训ppt ,大概花了7个工作日,走了一些弯路,问题总结: 开始一项工作前,对接清除核心要点(刚开网上搜罗一圈 拼凑了一份(将各个内容进行筛选整理) 反馈后不是领导想要的) 制作ppt前, ...