欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

Java 8 Stream进行实战总结及原理应用

程序员文章站 2022-05-17 12:50:23
...
小结本文探究了Stream的实现原理,介绍了怎么用Java 8 Stream的开源框架 StreamEx来解答*上一些经常被问到关于Java 8 Stream的问题:
  • Convert Java 8 List<V> into Map<K, V>

用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进行实战总结及原理应用的详细内容,更多请关注其它相关文章!

相关标签: java Stream