问题描述:
java.lang.IllegalStateException: Duplicate key UserEntity(username=1, password=123456)
问题分析:
1、使用Collectors.toMap()方法将List<UserEntity>集合转为Map<String,UserEntity>集合,List集合出现两个key值相同的情况时,会导致报错。
package com.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class UserEntity {
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
public UserEntity(String username, String password) {
this.password = password;
this.username = username;
}
}
public static void main(String[] args) {
List<UserEntity> userEntityList = new ArrayList<>();
userEntityList.add(new UserEntity("1", "123456"));
userEntityList.add(new UserEntity("1", "123"));
Map<String, UserEntity> userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getUsername, Function.identity()));
}
解决办法:
出现key重复的情况,保留第一个结果即可。
public static void main(String[] args) {
List<UserEntity> userEntityList = new ArrayList<>();
userEntityList.add(new UserEntity("1", "123456"));
userEntityList.add(new UserEntity("1", "123"));
Map<String, UserEntity> userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getUsername
, Function.identity(), (entity1, entity2) -> entity1)); }