首頁 >Java >java教程 >Java 8 Stream進行實戰總結及原理應用

Java 8 Stream進行實戰總結及原理應用

php是最好的语言
php是最好的语言原創
2018-07-27 09:22:232051瀏覽

 小結本文探討了Stream的實作原理,介紹瞭如何用Java 8 Stream的開源框架StreamEx來解答StackOverflow上一些常被問到關於Java 8 Stream的問題:

  • #Convert Java 8 Listd94943c0b4933ad8cac500132f64757f into Mapb56561a2c0bc639cf0044c0859afb88f

用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);
  • Custom thread pool in Java 8 parallel stream

##用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();

  • Java 8 Distinct by property

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

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

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

相關文章:

##Java之Lambda表達式與Stream類別簡單範例 

相關影片:

妙味茶館Javascript實戰影片教學  

                                   

以上是Java 8 Stream進行實戰總結及原理應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn