Convert List to Map Using Java
In this article, let’s check how we can convert a given List to a Java Map.
Suppose we have a User
class having name
and age
fields, and we create three User
objects and keep them in a list.
We want a map with user.name as map key, and user object as map value.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private Integer age;
}
// ...
User user1 = new User("Jack", 25);
User user2 = new User("Tom", 30);
User user3 = new User("Tom", 33);
List<User> list = Arrays.asList(user1, user2, user3);
There might be duplicates in our list, so we should be carefully while writing converting codes.
Plain Java For Loop
Map<String, User> map = new HashMap<>();
for (User u : list) {
if (!map.containsKey(u.getName())) {
map.put(u.getName(), u);
}
}
log.info("map: {}", map);
Java 8 Stream
Map<String, User> map = list.stream()
.collect(Collectors.toMap(User::getName, Function.identity());
log.info("map: {}", map);
Collectors.toMap()
will throw IllegalStateException
when the mapped keys contain duplicates, If the mapped keys might have duplicates, we can pass an aditional function parameter to resolve collisions between values.
Map<String, User> map = list.stream()
.collect(Collectors.toMap(User::getName, Function.identity(), (o1, o2) -> o2));
log.info("map: {}", map);
Apache Commons MapUtils.populateMap()
If you have Apache Commons Collections
library in your classpath, you can also use MapUtils.populateMap()
, which populates a Map using the supplied Transformers to transform the elements into keys and values.
MapUtils.populateMap(map, list, User::getName, o -> o);
log.info("map: {}", map);
Besides, this method helps us deal with duplicate data. From the source codes we can know that when there is duplicate data, only the last occurrence would be retained.
public static <K, V, E> void populateMap(final Map<K, V> map, final Iterable<? extends E> elements,
final Transformer<E, K> keyTransformer,
final Transformer<E, V> valueTransformer) {
final Iterator<? extends E> iter = elements.iterator();
while (iter.hasNext()) {
final E temp = iter.next();
map.put(keyTransformer.transform(temp), valueTransformer.transform(temp));
}
}
Google Guava Maps.uniqueIndex()
If you have Google Guava
library in your classpath, you can also use Maps.uniqueIndex()
.
But it is not a recomended method because it will also throw IllegalArgumentException
when there are multiple entries with same key.
try {
map = Maps.uniqueIndex(list, User::getName);
log.info("map: {}", map);
} catch (Exception e) {
log.error("", e);
}