Convert stream to Map

This example will show how to convert a 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.


class Item {

    String key;

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

    public String getKey() {
        return key;

List<Item> items;

public void setUp () {
    items = new ArrayList<>();
    items.add(new Item("ONE"));
    items.add(new Item("TWO"));
    items.add(new Item("THREE"));


public void stream_to_map() {

    Map<String, Item> map =
            Collectors.toMap(Item::getKey, item -> item));
    assertTrue(map.keySet().size() == 3);