EN
Java 8 - convert list of objects to map (from List<User> to Map<Long, User> - long to object / counter)
7 points
Quick solution - using simple lambda:
xxxxxxxxxx
1
List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));
2
3
Map<Long, User> usersMap = users.stream().collect(
4
Collectors.toMap(User::getUserId, user -> user));
5
6
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
7
System.out.println(usersMap);
Quick solution 2 - using Function.identity():
xxxxxxxxxx
1
List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));
2
3
Map<Long, User> usersMap2 = users.stream().collect(
4
Collectors.toMap(User::getUserId, Function.identity()));
5
6
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
7
System.out.println(usersMap2);
Full example:
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
import java.util.Map;
4
import java.util.function.Function;
5
import java.util.stream.Collectors;
6
7
public class Example {
8
9
public static void main(String[] args) {
10
11
List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));
12
13
// example 1 with lambda
14
Map<Long, User> usersMap = users.stream().collect(
15
Collectors.toMap(User::getUserId, user -> user));
16
17
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
18
System.out.println(usersMap);
19
20
// example 2 with Function.identity()
21
Map<Long, User> usersMap2 = users.stream().collect(
22
Collectors.toMap(User::getUserId, Function.identity()));
23
24
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
25
System.out.println(usersMap2);
26
}
27
28
private static class User {
29
private final long userId;
30
private final String name;
31
32
public User(long userId, String name) {
33
this.userId = userId;
34
this.name = name;
35
}
36
37
public long getUserId() {
38
return userId;
39
}
40
41
public String getName() {
42
return name;
43
}
44
45
46
public String toString() {
47
return "User{" +
48
"userId=" + userId +
49
", name='" + name + '\'' +
50
'}';
51
}
52
}
53
}