|
| 1 | +package com.baeldung.spliteratorAPI; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Spliterator; |
| 6 | +import java.util.concurrent.ExecutorService; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.stream.Collectors; |
| 9 | +import java.util.stream.IntStream; |
| 10 | +import java.util.stream.Stream; |
| 11 | +import java.util.stream.StreamSupport; |
| 12 | + |
| 13 | +public class Executor { |
| 14 | + public void executeCustomSpliterator() { |
| 15 | + Article article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), |
| 16 | + new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), |
| 17 | + new Author("Alice", 1), new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0); |
| 18 | + Stream<Author> stream = IntStream.range(0, article.getListOfAuthors() |
| 19 | + .size()) |
| 20 | + .mapToObj(article.getListOfAuthors()::get); |
| 21 | + System.out.println("count= " + countAutors(stream.parallel())); |
| 22 | + Spliterator<Author> spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); |
| 23 | + Stream<Author> stream2 = StreamSupport.stream(spliterator, true); |
| 24 | + System.out.println("count= " + countAutors(stream2.parallel())); |
| 25 | + } |
| 26 | + |
| 27 | + public void executeSpliterator() { |
| 28 | + Spliterator<Article> split1 = generateElements().spliterator(); |
| 29 | + Spliterator<Article> split2 = split1.trySplit(); |
| 30 | + ExecutorService service = Executors.newCachedThreadPool(); |
| 31 | + service.execute(new Task(split1)); |
| 32 | + service.execute(new Task(split2)); |
| 33 | + } |
| 34 | + |
| 35 | + private static int countAutors(Stream<Author> stream) { |
| 36 | + RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine); |
| 37 | + return wordCounter.getCounter(); |
| 38 | + } |
| 39 | + |
| 40 | + private List<Article> generateElements() { |
| 41 | + return Stream.generate(() -> new Article("Java")) |
| 42 | + .limit(35000) |
| 43 | + .collect(Collectors.toList()); |
| 44 | + } |
| 45 | +} |
0 commit comments