小結本文探討了Stream的實作原理,介紹瞭如何用Java 8 Stream的開源框架StreamEx來解答StackOverflow上一些常被問到關於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
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();
IntStreamEx.range(1, 1_000_000).parallel(new ForkJoinPool(2)) .filter(PrimesPrint::isPrime).toList();
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.of(persons).distinctBy(Person::getName);
Stream.of(objects) .filter(Client.class::isInstance) .map(Client.class::cast) .map(Client::getID) .forEach(System.out::println);
StreamEx.of(objects) .select(Client.class) .map(Client::getID) .forEach(System.out::println);
以上是Java 8 Stream進行實戰總結及原理應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!