/** * Performs stream processing on the input. */ public List<List<SearchResults>> processStream() { Stream<? extends CharSequence> inputStream = mInputList // Convert the list of input strings into a stream. .stream(); if (mParallelInput) // Convert the stream to a parallel stream. inputStream.parallel(); // Create a list of SearchResults that indicate which phrases // are found in the list of input strings. return inputStream // Process each input string to find all occurrences of // the search phrases. .map(this::processInput) // If a phrase was found add it to the list of results. .filter(not(List<SearchResults>::isEmpty)) // This terminal operation triggers aggregate operation // processing and returns a list of list of SearchResults. .collect(toList()); }
/** * Search the input for all occurrences of the @ wordsToFind and * print the results (if any). */ public void findAndPrintWords(List <String> wordsToFind) { // Create a list SearchResults corresponding to the index // where each word occurs in the input string. List<SearchResults> results = wordsToFind // Convert the list of words to find into a stream. .stream() // For each word to find create a stream of SearchResults // indicating the index (if any) where the word matched // the input. .map(this::searchForWord) // Filter out any SearchResults that are empty. .filter(not(SearchResults::isEmpty)) // This terminal operation triggers intermediate operation // processing and collects the SearchResults into a list. .collect(toList()); // Print the results; printResults(results); }
/** * This method searches the @a inputString for all occurrences of * the phrases to find. */ private List<SearchResults> processInput(CharSequence inputString) { // Get the section title. String title = getTitle(inputString); // Skip over the title. CharSequence input = inputString.subSequence(title.length(), inputString.length()); Stream<String> phraseStream = mPhrasesToFind // Convert the list of phrases to find into a stream. .stream(); if (mParallelPhrases) // Convert the stream to a parallel stream. phraseStream.parallel(); // Find all occurrences of phrase in the input string. return phraseStream // Find all indices where phrase matches the input data. .map(phrase -> searchForPhrase(phrase, input, title, mParallelSpliterator)) // Only keep a result that has at least one match. .filter(not(SearchResults::isEmpty)) // Filtering can also be done as // .filter(result -> result.size() > 0) // Terminate the stream and trigger the processing. .collect(toList()); }