Java 8 Stream API

Collectors

Collect to Map<key, value>

public static Map<String, Item> streamToOneToOne(Stream<Item> itemStream) {
  return itemStream.collect(Collectors.toMap(Item::getUuid, Function.identity()));
}

Collect to Map<key, List<value>>

Stream\ to Map\

public static Map<String, List<Item>> streamToOneToMany(Stream<Item> itemStream) {
  return itemStream.collect(groupingBy(Item::getUuid));
}

Stream\ to Map\

public static Map<String, List<String>> streamToOneToMany(Stream<Item> itemStream) {
  return itemStream.collect(groupingBy(Item::getUuid, Collectors.mapping(Item::getValue, Collectors.toList())));
}

Collect with join

List<Person> list = Arrays.asList(
  new Person("John", "Smith"),
  new Person("Anna", "Martinez"),
  new Person("Paul", "Watson ")
);

String joinedFirstNames = list.stream()
  .map(Person::getFirstName)
  .collect(Collectors.joining(", ")); // "John, Anna, Paul"

Last updated

Was this helpful?