Stream with Try example.
This commit is contained in:
parent
84fb527cc8
commit
979d80a56a
@ -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<Person> 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()
|
||||
);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user