Java 8 Streams: From List To Map
A list of POJOs:
public class Workshop {
private String name;
private int attendance;
public Workshop(String name, int attendance) {
this.name = name;
this.attendance = attendance;
}
public String getName() {
return name;
}
public int getAttendance() {
return attendance;
}
}
...can be directly converted into a Map using the built-in toMap Collector:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class CollectorsTest {
@Test
public void listToMap() {
List<Workshop> workshops
= Arrays.asList(
new Workshop("bootstrap", 21),
new Workshop("effective", 42)
);
Map<String, Integer> workshopsMap = workshops.
stream().
collect(Collectors.toMap(Workshop::getName,Workshop::getAttendance));
assertThat(workshopsMap.size(), is(2));
assertThat(workshopsMap.get("bootstrap"), is(21));
assertThat(workshopsMap.get("effective"), is(42));
}
}
See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Hi Adam,
Your code is working only if the Name is unique for each Workshop in the Collection (Otherwise an Exception will be thrown that the map-key is not unique).
If Name is not unique, following code might help:
Map<String, Set<Workshop>> map = workshops.stream()
.collect(Collectors.groupingBy(Workshop::getName, Collectors.mapping(Function.identity(), Collectors.toSet())));
Posted by Christian Thiel on January 29, 2016 at 08:47 AM CET #
The code will also throw an npe if the value is null, which is somewhat surprising for a Map. You are using int, so that is not happen in this case, but in other use cases with Object as a value it is possible.
Posted by Alex on January 30, 2016 at 07:02 AM CET #
Hi Adam,
I found this post very useful. Thank you!
I have a question, too:
Can we still convert easily if we had
private Person instructor;
and would like a Map of instructor names and attendance (assuming the field name exists in class Person)?
Posted by Cristina Fierbinteanu on October 14, 2016 at 12:07 PM CEST #
Nice Article
Posted by Yash on November 06, 2016 at 10:22 AM CET #