Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map List of objects to Map by [duplicate]

I want to group list of users by id() using Java Streams.

For example, I have List: new User(1L, "First"), new User(2L, "Second").

How can I group this list to get Map<Long, User>?

1L -> new User(1L, "First"),
2L -> new User(2L, "Second")

User.java

public final class User {
    final Long id;
    final String name;

    public User(final Long id, final String name) {
        this.id = id;
        this.name = name;
    }

    public Long id() {
        return this.id;
    }

    public String name() {
        return this.name;
    }
}
like image 476
Roman Cherepanov Avatar asked Oct 23 '25 15:10

Roman Cherepanov


1 Answers

If each ID is mapped to a single User, use Collectors.toMap:

Map<Long,User> users = list.stream().collect(Collectors.toMap(User::id,Function.identity()));
like image 176
Eran Avatar answered Oct 26 '25 05:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!