flatMap Function: Explained with Examples in Java
The 'flatMap()' function in programming is a higher-order function that applies a given function to each element of a collection and returns a flattened result. It's commonly used in functional programming and is available in many languages, including Java, JavaScript, Swift, and Scala.
The 'flatMap()' function takes a collection as input and applies a function to every element. The function's output is a new collection, which the 'flatMap()' function then flattens into a single collection. This means that if the function returns a collection of collections, 'flatMap()' will combine them into one.
For instance, let's say we have a list of strings, where each string represents a sentence:
List<String> sentences = Arrays.asList('Hello world', 'Goodbye world', 'The world is round');
We can utilize the 'flatMap()' function to split each sentence into words and create a flattened list of these words:
List<String> words = sentences
.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(' ')))
.collect(Collectors.toList());
// Output: ['Hello', 'world', 'Goodbye', 'world', 'The', 'world', 'is', 'round']
In this example, we first create a stream of sentences using the 'stream()' function. Then, we employ the 'flatMap()' function to split each sentence into words using 'Arrays.stream()' to generate a stream of words from each sentence. Finally, we use the 'collect()' function to assemble the flattened list of words into a new list.
原文地址: https://www.cveoy.top/t/topic/oNeY 著作权归作者所有。请勿转载和采集!