The third argument here is a BinaryOperator, where we can specify how we want collisions to be handled. collect(toMap(Function.identity(), String::length, (item, identicalItem) -> item)) In such cases with key collision, we should use toMap with another signature: Map result = givenList.stream() If it sees duplicate keys, it immediately throws an IllegalStateException. Note that toMap doesn’t even evaluate whether the values are also equal. }).isInstanceOf(IllegalStateException.class) ListWithDuplicates.stream().collect(toMap(Function.identity(), String::length)) So what happens if our collection contains duplicate elements? Contrary to toSet, toMap doesn’t silently filter duplicates, which is understandable because how would it figure out which value to pick for this key? List listWithDuplicates = Arrays.asList('a', 'bb', 'c', 'd', 'bb') collect(toMap(Function.identity(), String::length))įunction.identity() is just a shortcut for defining a function that accepts and returns the same value.