查看下面的代码:
public class DailyTest {
public static void main(String[] args) {
//
List<User> users = Lists.newArrayList(
new User(12L,"花花2"),
new User(13L,"花花3"),
new User(14L,"花花4"),
new User(15L,"花花5"),
new User(16L,"花花6"),
new User(17L,"花花7"),
new User(17L,"花花7")
);
// 转成map
Map<Long, User> map = users.stream().collect(Collectors.toMap(User::getId, user -> user));
System.out.println(map);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class User{
private Long id;
private String username;
}
我们使用的是java8的特性使用stream中的api吧list转换为map
但是运行的时候报了异常
异常如下:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key User(id=17, username=花花7)
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1254)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.wangye.powermock.DailyTest.main(DailyTest.java:26)
那么这是为什么呢?
是因为,你把user对象的id作为map的key,但是你的list中有两个id为17L的对象,所以就会报这个重复的key的异常
需要get的代码是下面这两行:
new User(17L,"花花7"),
new User(17L,"花花7")
所以使用这个Collectors.toMap的时候,一定要确定,作为可以的属性,不能重复
网友评论