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:
List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));
Map<Long, User> usersMap = users.stream().collect(
Collectors.toMap(User::getUserId, user -> user));
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
System.out.println(usersMap);
Quick solution 2 - using Function.identity():
List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));
Map<Long, User> usersMap2 = users.stream().collect(
Collectors.toMap(User::getUserId, Function.identity()));
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
System.out.println(usersMap2);
Full example:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List<User> users = Arrays.asList(new User(1, "Ann"), new User(2, "Tom"));
// example 1 with lambda
Map<Long, User> usersMap = users.stream().collect(
Collectors.toMap(User::getUserId, user -> user));
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
System.out.println(usersMap);
// example 2 with Function.identity()
Map<Long, User> usersMap2 = users.stream().collect(
Collectors.toMap(User::getUserId, Function.identity()));
// {1=User{userId=1, name='Ann'}, 2=User{userId=2, name='Tom'}}
System.out.println(usersMap2);
}
private static class User {
private final long userId;
private final String name;
public User(long userId, String name) {
this.userId = userId;
this.name = name;
}
public long getUserId() {
return userId;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", name='" + name + '\'' +
'}';
}
}
}