java Lambda表达式List快速转Map

工作经常会遇到list转为map的情况,可能我们只需要某个字段的值转为map集合,在jdk8以前,我们更多地可能会用for循环的方式,然后put到map中去,有了jdk8之后,我们可以使用简单的一句话,就可以搞定

List userList = new ArrayList<>();
		UserBean userBean = new UserBean("张三","热爱学习", 21);
		userList.add(userBean);
		
		 userBean = new UserBean("张三2","热爱学习2", 25);
		userList.add(userBean);
		
		 userBean = new UserBean("张三33","热爱学习3", 27);
		userList.add(userBean);
		
		 userBean = new UserBean("张三4","热爱学习2", 26);
		userList.add(userBean);
		
		System.out.println(userList);
		Map  map = 	    
        userList.stream().collect(Collectors.toMap(UserBean::getUserName, UserBean::getAge, 
        (key1,key2) ->key2));
		
		System.out.println(map);

关键语句:Map  map =     userList.stream().collect(Collectors.toMap(UserBean::getUserName, UserBean::getAge,(key1,key2) ->key2));解释
java Lambda表达式List快速转Map_第1张图片

key值重复报错信息:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key 21
    at java.util.stream.Collectors.lambda$throwingMerger$0(Unknown Source)
    at java.util.HashMap.merge(Unknown Source)
    at java.util.stream.Collectors.lambda$toMap$58(Unknown Source)
    at java.util.stream.ReduceOps$3ReducingSink.accept(Unknown Source)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.collect(Unknown Source)
    at test.LamdaTest.abc(LamdaTest.java:32)
    at test.LamdaTest.main(LamdaTest.java:12)

 

指定返回的Map为哪种类型:
        Map  map =     userList.stream().collect(Collectors.toMap(UserBean::getUserName, UserBean::getAge,(key1,key2) ->key2, LinkedHashMap::new));

要注意的坑:value的值不能为null,否则会报错

你可能感兴趣的:(java)