Sobes.tech
Junior

What Stream API collectors do you know? What does groupingBy return? How does it differ from toMap? How does toMap behave with duplicate keys?

sobes.tech AI

Answer from AI

In Java Stream API, there are several standard collectors, for example:

  • toList() — collects elements into a list.
  • toSet() — collects elements into a set.
  • toMap() — collects elements into a map.
  • groupingBy() — groups elements by a key, returning a Map with keys and lists of values.
  • joining() — joins strings.
  • summarizingInt() and similar — gather statistics.

groupingBy returns a Map<K, List<V>>, where the key is the result of the classification function, and the value is a list of elements in that group.

The difference between groupingBy and toMap is that toMap creates a Map where each key corresponds to exactly one value, whereas groupingBy groups multiple elements under one key into a collection.

When using toMap with duplicate keys, an IllegalStateException is thrown by default. To avoid this, you can pass a third parameter — a merge function, for example:

Map<String, String> map = list.stream()
    .collect(Collectors.toMap(
        item -> item.getKey(),
        item -> item.getValue(),
        (v1, v2) -> v2)); // in case of duplicate keys, take the last value

Without a merge function, duplicate keys will cause an error.