1.创建Person类

package com.xkzhangsan.normal.collectors;

public class Person {

    private Integer id;
private String name;
private Integer score;
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 Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
} @Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", score=" + score + "]";
} }

2.创建测试类ListToMap

package com.xkzhangsan.normal.collectors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors; public class ListToMap { public static void main(String[] args) {
//创建list
List<Person> personList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person p = new Person();
p.setId(i);
p.setName("p"+i);
p.setScore(i*10);
personList.add(p);
} //添加和id=8相同对象score值不同
Person p = new Person();
p.setId(8);
p.setName("p"+8);
p.setScore(88);
personList.add(p); System.out.println("list:========================");
personList.stream().forEach(System.out::println); //转换为HashMap
Map<Integer, Person> map = personList.stream().collect(Collectors.toMap(Person::getId, d->d, (oldValue, newValue)->newValue));
System.out.println("hashMap:========================");
map.entrySet().stream().forEach(System.out::println); //转换为TreeMap
Map<Integer, Person> treeMap = personList.stream().collect(Collectors.toMap(Person::getId, d->d, (oldValue, newValue)->newValue, TreeMap::new));
System.out.println("treeMap:========================");
treeMap.entrySet().stream().forEach(System.out::println);
} }

3.测试结果

list:========================
Person [id=0, name=p0, score=0]
Person [id=1, name=p1, score=10]
Person [id=2, name=p2, score=20]
Person [id=3, name=p3, score=30]
Person [id=4, name=p4, score=40]
Person [id=5, name=p5, score=50]
Person [id=6, name=p6, score=60]
Person [id=7, name=p7, score=70]
Person [id=8, name=p8, score=80]
Person [id=9, name=p9, score=90]
Person [id=8, name=p8, score=88]
hashMap:========================
0=Person [id=0, name=p0, score=0]
1=Person [id=1, name=p1, score=10]
2=Person [id=2, name=p2, score=20]
3=Person [id=3, name=p3, score=30]
4=Person [id=4, name=p4, score=40]
5=Person [id=5, name=p5, score=50]
6=Person [id=6, name=p6, score=60]
7=Person [id=7, name=p7, score=70]
8=Person [id=8, name=p8, score=88]
9=Person [id=9, name=p9, score=90]
treeMap:========================
0=Person [id=0, name=p0, score=0]
1=Person [id=1, name=p1, score=10]
2=Person [id=2, name=p2, score=20]
3=Person [id=3, name=p3, score=30]
4=Person [id=4, name=p4, score=40]
5=Person [id=5, name=p5, score=50]
6=Person [id=6, name=p6, score=60]
7=Person [id=7, name=p7, score=70]
8=Person [id=8, name=p8, score=88]
9=Person [id=9, name=p9, score=90]

4.注意事项

(1)list转map要注意重复对象,map转换方法要选择带mergeFunction参数的方法,如果key值重复,做合并处理,不然会抛异常!可以做到去重效果。

比如上面故意添加和id=8相同对象score为88,值不同。在map转换方法mergeFunction 为(oldValue, newValue)->newValue 使用新对象替换已有老对象,可以看到转换后id8的对象score变为88。

(2)list转map默认转换为HashMap,可以选择带mapSupplier参数的方法,选择要转换为的map类型。

比如上面TreeMap::new,选择转换为TreeMap。

github地址:https://github.com/xkzhangsan/java8-practice

java8使用stream的collect进行list转map注意事项的更多相关文章

  1. java8之stream

    lambda表达式是stream的基础,初学者建议先学习lambda表达式,http://www.cnblogs.com/andywithu/p/7357069.html 1.初识stream 先来一 ...

  2. Java8 Lambda/Stream使用说明

    一.Stream流1. 流的基本概念 1.1 什么是流?流是Java8引入的全新概念,它用来处理集合中的数据,暂且可以把它理解为一种高级集合.众所周知,集合操作非常麻烦,若要对集合进行筛选.投影,需要 ...

  3. Java8的Stream流(一) --- 基础用法

    Java8中的Stream Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象. Stream的特性及优点: 无存储. Stream不是一种数据 ...

  4. Java8的Stream API使用

    前言 这次想介绍一下Java Stream的API使用,最近在做一个新的项目,然后终于可以从老项目的祖传代码坑里跳出来了.项目用公司自己的框架搭建完成后,我就想着把JDK版本也升级一下吧(之前的项目, ...

  5. JAVA8之 Stream 流(四)

    如果说前面几章是函数式编程的方法论,那么 Stream 流就应该是 JAVA8 为我们提供的最佳实践. Stream 流的定义 Stream 是支持串行和并行操作的一系列元素.流操作会被组合到流管道中 ...

  6. Java8之Stream详解

    Java8中提供了Stream对集合操作作出了极大的简化,学习了Stream之后,我们以后不用使用for循环就能对集合作出很好的操作.   一.流的初始化与转换   Java中的Stream的所有操作 ...

  7. java8的stream功能及常用方法

    Java8中stream对集合操作做了简化,用stream操作集合能极大程度简化代码.Stream 就如同一个迭代器(Iterator),单向,不可往复,数据只能遍历一次,遍历过一次后就用尽了. 一. ...

  8. java8中stream的map和flatmap的理解

    转自https://blog.csdn.net/wynjauu/article/details/78741093 假如我们有这样一个需求给定单词列表["Hello","W ...

  9. Java8的Stream方法findAny空指针异常(NullPointerException)实例对比

    实战介绍 学习完Java8的Stream方法,可能你正准备大展身手,却发现遇到不少问题,本篇文章为大家带来一个findAny方法抛出java.lang.NullPointerException的场景. ...

随机推荐

  1. 逆向破解之160个CrackMe —— 031

    CrackMe —— 031 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...

  2. django model content_type 使用

    一.关于content_type 使用 1.引入模块在models from django.db import models from django.contrib.contenttypes.mode ...

  3. python的continue和pass的区别

    a = 'pythyon' i = 2 for element in a: if element == 'y': pass i = 3 else: print(element+str(i)) 结果: ...

  4. html--JavaScript之DOM (文档对象模型)

    一.简介 当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model). HTML DOM 定义了用于 HTML 的一系列标准的对象,以及访问和处理 HTML 文档的标 ...

  5. ESA2GJK1DH1K升级篇: STM32远程乒乓升级,基于(WIFI模块AT指令TCP透传方式),定时访问升级

    前言 学习此代码所需: 实现功能概要 定时使用http访问云端的程序版本,如果版本不一致,然后通过http下载最新的升级文件,实现升级. 测试准备工作(默认访问我的服务器,改为自己的服务器,请看后面说 ...

  6. SqlServer事务语法及使用方法(转)

    原博:http://blog.csdn.net/xiaouncle/article/details/52891563 事务是关于原子性的.原子性的概念是指可以把一些事情当做一个不可分割的单元来看待.从 ...

  7. js 压缩图片(只缩小体积,不更改图片尺寸)

      1.情景展示 如上图所示,点击上传图片按钮,调用手机摄像头拍照功能. <input onchange="javascript:imgFun.uploadPicture();&quo ...

  8. [算法模板]SOS DP

    [算法模板]SOS DP 正文 SOS-DP(\(\text{Sum over Subsets}\))是用来解决这样的问题的: 其实就是子集和DP.上面每个\(F[mask]\)里面包含了\(mask ...

  9. java语言总结

    优点: 安全(废弃指针) 任何一个学过C或者C++的人都知道指针的操作对于他们是很重要的,指针能够支持内存的直接操作,这样的直接操作能够带来的是效率上的提高.但是任何一个东西都是有副作用的,指针给程序 ...

  10. C# ini配置文件操作类

    /// <summary> /// INI文件操作类 /// </summary> public class IniFileHelper { /// <summary&g ...