[Solved] stream Convert list to map Error: java.lang.IllegalStateException: Duplicate key

I background

In many scenarios, the data of List needs to be transformed into the key-value pairs of Map scenarios to facilitate quick query data. For example: the need to query the corresponding person name details scenario according to the work number. There are two kinds of scenarios, the first one is to query the database once by each work number, which is obviously not reasonable because it is not good for DB pressure and connection. The second will be a collection of work number (need to consider the volume of data scenarios, Oracle supports a maximum of one thousand, mysql, although no online, but consider the performance and memory consumption need to consider the upper limit recommended 1000 below), the next is the second way to expand.

Translated with www.DeepL.com/Translator (free version)

II Development practice

List<User> userList = new ArrayList<>();

userList.add(User.builder().id(123).name("TEST123").build());

userList.add(User.builder().id(1231).name("TEST1231").build());

userList.add(User.builder().id(1232).name("TEST1232").build());

userList.add(User.builder().id(1233).name("TEST1233").build());

userList.add(User.builder().id(1234).name("TEST1234").build());

1.The stream implementation was not available before Java 1.8

Map<String, Long> idNameMap = new HashMap<String, Long>();

for(User user : userList ){

     idNameMap.put(user.getName(),  user.getId());

}

return idNameMap ;

2.Java 1.8 onwards supports stream implementation

return userList.stream().collect(Collectors.toMap(User::getName, User::getId);

III Existing problems

If you use the 2.1 way, the possible problems, if there are two data with the same name in the data, it will report an error java.lang.IllegalStateException: Duplicate key.

When using stream stream, it will not overwrite the data directly like the above way, but will report an error. So it needs to be optimized as

return userList.stream().collect(Collectors.toMap(User::getName, User::getId , (entity1, entity2) -> entity1);

It can solve the problem of error reporting.

Read More: