Home  >  Article  >  Java  >  Java 8 Stream practical summary and principle application

Java 8 Stream practical summary and principle application

php是最好的语言
php是最好的语言Original
2018-07-27 09:22:231981browse

Summary This article explores the implementation principle of Stream and introduces how to use the open source framework StreamEx of Java 8 Stream to answer some frequently asked questions about Java 8 Stream on StackOverflow:

  • Convert Java 8 Listd94943c0b4933ad8cac500132f64757f into Mapb56561a2c0bc639cf0044c0859afb88f

##Use JDK Stream API:

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

Use StreamEx API:

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

  • Custom thread pool in Java 8 parallel stream

Use 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();

Use StreamEx API:

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

  • Java 8 Distinct by property

Use 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));

Use StreamEx API:

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

  • Is it possible to cast a Stream in Java 8?

Use JDK Stream API:

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

Use StreamEx API:

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

Related articles:

Simple examples of Lambda expressions and Stream classes in Java

Related videos:

Miaowei Tea House Javascript Practical Video Tutorial

The above is the detailed content of Java 8 Stream practical summary and principle application. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn