Situation:
You have a list of users, and you need to create a map where each user’s ID is the key and the user object is the value.
Solution:
List<User> users = Arrays.asList(new User(1, "Alice"), new User(2, "Bob"));
Map<Integer, User> userMap = users.stream()
.collect(Collectors.toMap(User::getId, Function.identity()));
System.out.println(userMap);
Explanation:
This code uses Java Streams to transform the list of users into a map. User::getId
is used as the key, and Function.identity()
ensures the user object itself becomes the value.
Result:
{1=User{id=1, name='Alice'}, 2=User{id=2, name='Bob'}}
See you in the next tip !
Leave a Reply