1、指定key-value,value是对象中的某个属性值。

 Map<Integer,String> userMap = userList.stream().collect(Collectors.toMap(User::getId,User::getName));

2、指定key-value,value是对象本身

User->User 是一个返回本身的lambda表达式

Map<Integer,User> userMap = userList.stream().collect(Collectors.toMap(User::getId,User->User));

Function.identity()是简洁写法,也是返回对象本身

Map<Integer,User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

3、返回其他Map

解决了Key冲突并转为了TreeMap

userList.stream().collect(Collectors.toMap(User::getName, Function.identity(), (oldVal, newVal) -> newVal, TreeMap::new));

4、解决重复key问题

如果生成Map时有重复key(通过key类型的equals方法来判断)就会报错:java.lang.IllegalStateException: Duplicate key。

当发生重复时这里选择第二个key覆盖第一个key的value值,当然如果需要第一个key的value值那就选择oldKey(可提前先进行指定规则的排序)

Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(oldKey,newKey)->newKey));

PS:当然也可以提前将集合进行去重处理(stream根据指定字段去重)再进行简单的toMap操作。

5、其他示例

  • 重复时将前面的value 和后面的value拼接起来
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));

//或者将其值相加
Map<String, BigDecimal> map = list.stream().collect(Collectors.toMap(Person::getNo, Person::amount,BigDecimal::add));
  • value转为其他DTO实体并解决key重复问题
Map<Integer, ProductCategoryResultDTO> resultDTOMap = byCategoryFidAndEnvironmentTag.stream()
.collect(Collectors.toMap(ProductCategory::getCategoryId, v -> {
ProductCategoryResultDTO productCategoryResultDTO = new ProductCategoryResultDTO();
productCategoryResultDTO.setStatus(v.getUplowState());
return productCategoryResultDTO;
}, (key1, key2) -> key2));
  • 代码实战:
public static void main(String[] args) throws JsonProcessingException {
UserInfo u1 = new UserInfo(1, "张三");
UserInfo u2 = new UserInfo(2, "李四");
UserInfo u3 = new UserInfo(3, "王五");
UserInfo u4 = new UserInfo(4, "赵六1");
UserInfo u5 = new UserInfo(4, "赵六2");
List<UserInfo> list = Arrays.asList(u1,u2,u3,u4,u5); Map<Integer, String> map = list.stream()
.collect(Collectors.toMap(UserInfo::getId, UserInfo::getUserName, (key1, key2) -> key1 + "," + key2));
String mapStr = new ObjectMapper().writeValueAsString(map);
System.out.println(mapStr); Set<Object> set = new HashSet<>();
Map<Integer, String> map1 = list.stream()
.collect(Collectors.toMap(UserInfo::getId, UserInfo::getUserName, (key1, key2) -> {
set.add(key1);
return key1;
}));
System.out.println(new ObjectMapper().writeValueAsString(map1));
System.out.println("set:" + set);
}

执行结果:

stream流中toMap()api和Duplicate key问题的更多相关文章

  1. Stream流中的常用方法_Foreach-Stream流中的常用方法_filter

    Stream流中的常用方法_Foreach 流模型的操作很丰富,这里介绍一些常用的API.这些方法可以被分成两种︰·延迟方法∶返回值类型仍然是Stream,接口自身类型的方法,因此支持链式调用.(除了 ...

  2. JDK 8 中Stream流中的去重的方法

    JDK 8 中Stream流中去重的方法 1.简单的去重,可以使用distinct()方法去重,该方法是通过比较equals和hashcode值去去重, 2.复杂的去重, 例如,在一个JavaBean ...

  3. 【JDK8】JDK 8 中Stream流中的去重的方法

    JDK 8 中Stream流中去重的方法 1.简单的去重,可以使用distinct()方法去重,该方法是通过比较equals和hashcode值去去重, 2.复杂的去重, 例如,在一个JavaBean ...

  4. Stream流的特点_只能使用一次和Stream流中的常用方法_map

    Stream流的特点_只能使用一次 public class FilterStudy04 { public static void main(String[] args) { //创建一个Stream ...

  5. Stream流中的常用方法foeEach和Stream流中的常用方法filter

    延迟方法:返回值类型仍然是Stream接口自身类型的方法,因此支持链式调用.(除了中介方法外,其余方法均为延迟方法) 终结方法:返回值类型不再是Stream接口自身类型的方法,因此不再支持类似Stri ...

  6. Stream流中的常用方法_skip-Stream流中的常用方法_concat

    Stream流中的常用方法_skip 如果希望跳过前几个元素,可以使用skip方法获取一个截取之后的新流∶ 如果流的当前长度大于n,则跳过前n个;否则将会得到一个长度为0的空流.基本使用: Strea ...

  7. Stream流的特点_只能用一次-Stream流中的常用方法_map

    Stream流的特点_只能用一次 Stream流属于管道流,只能被消费(使用)一次 第一个stream流调用完毕方法,数据就会流转到下一个stream上 而这时第一个stream流已经使用完毕,就会关 ...

  8. node.js中stream流中可读流和可写流的使用

    node.js中的流 stream 是处理流式数据的抽象接口.node.js 提供了很多流对象,像http中的request和response,和 process.stdout 都是流的实例. 流可以 ...

  9. mysql系列十三、mysql中replace into和duplicate key的使用区

    一.创建测试表 1.创建唯一索引"b" CREATE TABLE `test2` ( `id` int(10) NOT NULL AUTO_INCREMENT, `a` varch ...

  10. Stream流中的常用方法

    count package com.yang.Test.StreamStudy; import java.util.stream.Stream; /** * 统计荷属:count * 正如旧集合Col ...

随机推荐

  1. 埃尼阿克ENIAC与计算机发展,及信息技术发展史

    一.埃尼阿克ENIAC 第二次世界大战期间,国军方为了研发新型的大炮和导弹,设立了"弹道研究实验室".实验室为了计算炮弹弹道,用了200多人加班加点进行计算,速度依感无法达到军方要 ...

  2. 有关终端Github无法访问,connection timed out:443等问题

    有关终端Github无法访问,connection timed out:443等问题 SSL_connect: Operation timed out in connection to github. ...

  3. Java 项目愚蠢的分层及解决方案

    <整洁架构之道>的最后一章<细节决定成败>又在讨论 Javaer 永恒的问题:分层后 DAO Service Controller 应该按功能分包还是按层分包. 按功能分包的人 ...

  4. Scrum 和我主张的管理方式的同与异

    虽然零零星星接触过scrum的一些知识,之前并没有深入了解过.这次机缘巧合,将 Jeff Sutherland 的<用一半的时间做两倍的事>拜读完毕,感觉 scrum 的做法其实很多和我自 ...

  5. Linux打印显示时间

    Linux打印显示时间具体使用参数如下: 1.输出当前年月日echo $(date +%F)2.输出当前时间(时分)echo $(date +%R)3.输出当前时间(时分秒)echo $(date + ...

  6. Qt自定义控件集成到全平台QtCreator效果图

  7. GNU Make中CPPFLAGS和CXXFLAGS之间的区别

    GNU Make 是一个流行的构建工具,用于编译和链接源代码.在 GNU Make 中,CPPFLAGS 和 CXXFLAGS 都是用于指定编译器选项的变量.它们之间的主要区别在于它们分别适用于 C ...

  8. 🎉 夜莺监控突破一万 star,这是汗水,也是鞭策

    夜莺监控项目在上周突破了一万 star,算是一个小小的里程碑.在开源领域,通常把 star 数量看作项目的繁荣指标,star 数量越多,说明愿意关注你的人越多.这个数字的背后,是一群人对你的鼓励.认可 ...

  9. Win2D 投影效果 ShadowEffect

    <Page x:Class="Win2DDemo.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/ ...

  10. jwt-shiro-springsecurity-oauth2对比

    1 实现token的方式概述 在cookie\session\token辨析一文已经知道了token这个概念,里面简单说明了token的组成就是数据+签名,给出了token实现身份验证的流程,并且详细 ...