Map<String,List<String>>map=list.stream().collect(Collectors.toMap(Person::getId,p->{List<String>getNameList=newArrayList<>();getNameList.add(p.getName());returngetNameList;},(List<String>value1,List<String>value2)->{value1.addAll(value2);returnvalue1;}));System.out.println(map); 输...
如果我们要求map的顺序要按照list的执行的话,我们就要转map的时候指定map的具体实现。 Map<String, User> maps3 = list.stream().collect (Collectors.toMap(User::getName,Function.identity(),(k1, k2) -> k1,LinkedHashMap::new)); 输出结果 {pangHu=User{name='pangHu', age=18}, piKaQiu=User{name=...
publicstaticvoidmain(String[] args) {//自定义function函数,自定义消费函数Stream.of("1").map(e->e+")").forEach(e->System.out.println(e));//forEach 引用消费函数Stream.of("1").map(e->e+")").forEach(System.out::println); Stream.of("1").mapToInt(e->Integer.valueOf(e)).forE...
public static void main(String[] args) throws Exception { List<String> names = Lists.newArrayList("Answer", "AnswerAIL", "AI"); Map<String, Integer> map = names.stream().collect(Collectors.toMap(v -> v, v -> 1)); System.out.println(map); } } 1. 2. 3. 4. 5. 6. 7. ...
//将list转换map Map<String,String>map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName)); System.out.println(map); 1. 2. 3. 4. 5. 6. 7. 8. 9. 输出结果为: 注意:用Collectors的toMap方法转换List,一般会遇到两个问题。一个是转换map,key重复问题;另一个是空指针异...
Java8中将List优雅地转Map的多种方式 在代码开发过程中,我们经常需要将List中的元素根据某一个字段进行分组,这个时候,我们就需要把List来转换成Map来满足我们的业务需求,通常我们转换的场景有以下几种: 一、List<Object>转Map<String,String> 二、List<Object>转Map<String,Object>(返回对象本身)...
将List 转为 Map<K, V> publicstaticvoidmain(String[] args) throwsException{List<User> users =newArrayList<>();for(int i =0; i <3; i++) { users.add(newUser("answer"+ i,newRandom().nextInt(100))); }System.out.println(JSON.toJSONString(users));System.out.println();Map<String,...
Map<String, String> map = sdsTests.stream().collect(Collectors.toMap(SdsTest::getName,SdsTest::getAge)); System.out.println(map.toString()); --- 运行错误:Exceptionin thread"main"java.lang.IllegalStateException: Duplicate key aaa at java....
HashMap<String,String> map中 key是一个String,value也是一个String,即定义了一个Map集合变量 看下面的代码了解区别,常见的使用方法:package com.test.annotation;import java.util.*;public classListTest{ public staticvoid main(String[] args) { List<Map<String, Object>> listMaps = new ArrayLi...
在实际项目中我们经常会用到 List 转 Map 操作,在过去我们可能使用的是 for 循环遍历的方式。举个例子:先定义类: // 简单对象 @Accessors(chain = true) // 链式方法 @lombok.Data class User { private String…