Transform a List to a Map of ID and Object

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 !


Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect