Java 8 Stream之實戰篇

lihy70發表於2019-01-19

在這片文章裡,主要介紹怎麼用Java 8 Stream的開源框架 StreamEx來解答StackOverflow上一些經常被問到關於Java 8 Stream的問題:

用JDK Stream API:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));

用StreamEx API:

Map<String, Choice> result = StreamEx.of(choices).toMap(Choice::getName);

用JDK Stream API:

ForkJoinPool forkJoinPool = new ForkJoinPool(2);
forkJoinPool.submit(() ->
    //parallel task here, for example
    IntStream.range(1, 1_000_000).parallel().filter(PrimesPrint::isPrime).collect(toList())
).get();

用StreamEx API:

IntStreamEx.range(1, 1_000_000).parallel(new ForkJoinPool(2))
           .filter(PrimesPrint::isPrime).toList();

用JDK Stream API:

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}

persons.stream().filter(distinctByKey(Person::getName));

用StreamEx API:

StreamEx.of(persons).distinctBy(Person::getName);

用JDK Stream API:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

用StreamEx API:

StreamEx.of(objects)
    .select(Client.class)
    .map(Client::getID)
    .forEach(System.out::println);

相關文章