From 979d80a56a4cbdfee4d692e0796f6f217fbeadad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Dyda?= Date: Thu, 17 Nov 2022 10:54:34 +0100 Subject: [PATCH] Stream with Try example. --- .../pl/amu/edu/demo/stream/StreamExample.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java diff --git a/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java b/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java new file mode 100644 index 0000000..247c55d --- /dev/null +++ b/demo/03/src/main/java/pl/amu/edu/demo/stream/StreamExample.java @@ -0,0 +1,65 @@ +package pl.amu.edu.demo.stream; + +import io.vavr.control.Try; +import pl.amu.edu.demo.data.Address; +import pl.amu.edu.demo.data.Housing; +import pl.amu.edu.demo.data.Person; + +import java.time.LocalDate; +import java.util.OptionalDouble; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +public class StreamExample { + + public static void main(String[] args) { + new StreamExample().run(); + } + + private void run() { + // Huge number of threads! + getPeople().parallel().mapToInt(Person::getAge).average().ifPresent(System.out::println); + // Better solution, limiting the number of threads + try (var pool = new ForkJoinPool(8)) { + var maybeAverageAgeFuture = pool.submit( + () -> getPeople().parallel().mapToInt(Person::getAge).average() + ); + // io.vavr.control.Try + var triedAverageAge = Try.of( + () -> maybeAverageAgeFuture.get(30, TimeUnit.SECONDS) + ).map(OptionalDouble::orElseThrow); + if (triedAverageAge.isSuccess()) { // there is also isFailure() + System.out.println(triedAverageAge.get()); // instead of if, one can use getOrElse() + } + } + + } + + private Stream getPeople() { + var personPrototype = Person.builder() + .housing( + Housing.builder().isApartment(false).area(54321.0).address( + Address.builder().build() + ).build() + ); + return Stream.of( + personPrototype + .displayName("Maksymilian Paradys") + .birthDate(LocalDate.of(1958, 10, 25)) + .build(), + personPrototype + .displayName("Albert Starski") + .birthDate(LocalDate.of(1958, 4, 6)) + .build(), + personPrototype + .displayName("Lamia Reno") + .birthDate(LocalDate.of(2017, 3, 11)) + .build(), + personPrototype.displayName("Emma Dax") + .birthDate(LocalDate.of(2014, 11, 17)) + .build() + ); + } + +}