Convert stream to Map

This example will show how to convert a java.util.stream.Stream into a Map in Java 8. A Collector is a reduction operation that will accumulate elements from a stream into a cumulative result. We must supply a Collector to gather the Stream’s items into Map which we can do by using a connivence method toMap() from the Collectors utility. The first parameter required by toMap is a function that defines the key. It asks, what value in the object will be the key in the map. The second value is a value mapper which will provide the value to the map.

In the set up we create a Item object and initialize an ArrayList to be used in the snippet below.

Setup

class Item {

    String key;

    public Item(String key) {
        super();
        this.key = key;
    }

    public String getKey() {
        return key;
    }
}

List<Item> items;

@Before
public void setUp () {

    items = new ArrayList<>();

    items.add(new Item("ONE"));
    items.add(new Item("TWO"));
    items.add(new Item("THREE"));
}

toMap

@Test
public void stream_to_map() {

    Map<String, Item> map = items.stream().collect(
            Collectors.toMap(Item::getKey, item -> item));

    assertTrue(map.keySet().size() == 3);
}