Skip to content

Instantly share code, notes, and snippets.

@nicokosi
Last active July 29, 2020 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicokosi/d65f6a880587d085d844806368e03815 to your computer and use it in GitHub Desktop.
Save nicokosi/d65f6a880587d085d844806368e03815 to your computer and use it in GitHub Desktop.
JShell experimentations with Java 14 collectors from streams API
// Inspired by Venkat Subramaniam's talk "LJC Virtual Meetup: Exploring Collectors", similar to this former one: https://www.youtube.com/watch?v=z1eaTv_FASg
// See javadoc for Collectors: https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/stream/Collectors.html
// Run me with Java 14 via 'jshell --enable-preview'
record Person(String name, int age) {}
var persons = List.of(
new Person("Sarah", 14),
new Person("Venkat", 30),
new Person("Sarah", 65),
new Person("Farid", 12));
import static java.util.stream.Collectors.*
// List all persons (mutable or not)
persons.stream()
.collect(toList())
persons.stream()
.collect(toUnmodifiableList())
// Filter
persons.stream()
.filter(p -> p.age() < 20)
.collect(toList())
// Filter and map
persons.stream()
.map(Person::age)
.collect(toSet())
// Join
persons.stream()
.map(Person::name)
.collect(joining(", "))
// Group by
persons.stream()
.collect(groupingBy(Person::age))
// Sum by
persons.stream()
.collect(groupingBy(Person::name, summingInt(Person::age)))
// Partition by
persons.stream()
.collect(partitioningBy(p -> p.age() < 18))
// Tee (merge collectors)
persons.stream()
.collect(
teeing(
filtering(
person -> person.age() < 18,
toList()),
filtering(
person -> person.age() >= 65,
toList()),
(underage, retired) -> List.of(underage.size(), retired.size())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment