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

Java 8 Stream practical summary and principle application

php是最好的语言
Release: 2018-07-27 09:22:23
Original
2141 people have browsed it

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 List<V> into Map<K, V>

##Use JDK Stream API:

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

Use StreamEx API:

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

  • 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();
Copy after login

Use StreamEx API:

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

  • 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));
Copy after login

Use StreamEx API:

StreamEx.of(persons).distinctBy(Person::getName);
Copy after login

  • 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);
Copy after login

Use StreamEx API:

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

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!

Related labels:
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template