📜  在Java中使用示例流 flatMap()

📅  最后修改于: 2022-05-13 01:54:22.514000             🧑  作者: Mango

在Java中使用示例流 flatMap()

Stream flatMap(函数 mapper)返回一个流,其中包含将此流的每个元素替换为通过将提供的映射函数应用于每个元素而生成的映射流的内容的结果。 Stream flatMap(函数 mapper) 是一个中间操作。这些操作总是懒惰的。在 Stream 实例上调用中间操作,在它们完成处理后,它们给出一个 Stream 实例作为输出。

注意:每个映射的流在其内容放入此流后关闭。如果映射流为空,则使用空流。

flatMap() V/s map() :
1) map() 接受一个 Stream 并将其转换为另一个 Stream。它对 Stream 的每个元素应用一个函数,并将返回值存储到新的 Stream 中。它不会使流变平。但是 flatMap() 是映射和平面操作的组合,即,它将函数应用于元素并将它们展平。
2) map() 仅用于变换,而 flatMap() 用于变换和展平。

句法 :

 Stream flatMap(Function> mapper)

where, R is the element type of the new stream.
Stream is an interface and T is the type 
of stream elements. mapper is a stateless function 
which is applied to each element and the function
returns the new stream.

示例 1:带有提供映射函数。

// Java code for Stream flatMap
// (Function mapper) to get a stream by
// replacing the stream with a mapped
// stream by applying the provided mapping function.
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a List of Strings
        List list = Arrays.asList("5.6", "7.4", "4",
                                          "1", "2.3");
  
        // Using Stream flatMap(Function mapper)
        list.stream().flatMap(num -> Stream.of(num)).
                         forEach(System.out::println);
    }
}

输出 :

5.6
7.4
4
1
2.3

示例 2: flatMap()函数提供了将字符串映射到位置 2 的字符的操作。

// Java code for Stream flatMap
// (Function mapper) to get a stream by
// replacing the stream with a mapped
// stream by applying the provided mapping function.
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a List of Strings
        List list = Arrays.asList("Geeks", "GFG",
                                 "GeeksforGeeks", "gfg");
  
        // Using Stream flatMap(Function mapper)
        list.stream().flatMap(str -> 
                         Stream.of(str.charAt(2))).
                         forEach(System.out::println);
    }
}

输出 :

e
G
e
g

flatMap() 是如何工作的?

正如文章中已经讨论的那样,flatMap() 是地图和平面操作的组合,即,它首先应用地图函数,然后将结果展平。让我们考虑一些例子来理解什么是扁平化流。
示例 1:
展平前的清单:

[ [2, 3, 5], [7, 11, 13], [17, 19, 23] ]

该列表有 2 个级别,由 3 个小列表组成。展平后,它变成了“一层”结构,如图所示:

[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ] 

示例 2:
展平前的清单:

[ ["G", "E", "E"], ["K", "S", "F"], ["O", "R", "G"], ["E", "E", "K", "S"] ]

该列表有 3 个级别,由 4 个小列表组成。展平后,它变成了“一层”结构,如图所示:

["G", "E", "E", "K", "S", "F", "O", "R", "G", "E", "E", "K", "S"] 

简而言之,我们可以说,如果展平前有一个<<数据类型>>的List的Stream ,那么在应用flatMap()时,展平后返回的是<<数据类型>>的Stream
应用 :

// Java code for Stream flatMap(Function mapper) 
import java.util.*;
import java.util.stream.Collectors;
  
class GFG
{   
    // Driver code
    public static void main(String[] args)
    {   
        // Creating a list of Prime Numbers
        List PrimeNumbers = Arrays.asList(5, 7, 11,13);
          
        // Creating a list of Odd Numbers
        List OddNumbers = Arrays.asList(1, 3, 5);
          
        // Creating a list of Even Numbers
        List EvenNumbers = Arrays.asList(2, 4, 6, 8);
  
        List> listOfListofInts =
                Arrays.asList(PrimeNumbers, OddNumbers, EvenNumbers);
  
        System.out.println("The Structure before flattening is : " +
                                                  listOfListofInts);
          
        // Using flatMap for transformating and flattening.
        List listofInts  = listOfListofInts.stream()
                                    .flatMap(list -> list.stream())
                                    .collect(Collectors.toList());
  
        System.out.println("The Structure after flattening is : " +
                                                         listofInts);
    }
}

输出 :

The Structure before flattening is : [[5, 7, 11, 13], [1, 3, 5], [2, 4, 6, 8]]
The Structure after flattening is : [5, 7, 11, 13, 1, 3, 5, 2, 4, 6, 8]