Stream flatMapToInt() en Java con ejemplos

Stream flatMapToInt(Function mapper) devuelve un IntStream que consta de los resultados de reemplazar cada elemento de este flujo con el contenido de un flujo mapeado producido al aplicar la función de mapeo proporcionada a cada elemento. Stream flatMapToInt (Mapeador de funciones) es una operación intermedia . Estas operaciones son siempre perezosas. Las operaciones intermedias se invocan en una instancia de Stream y, una vez que finalizan su procesamiento, dan una instancia de Stream como salida.

Nota: cada transmisión asignada se cierra después de que su contenido se haya colocado en esta transmisión. Si una secuencia asignada es nula, en su lugar se utiliza una secuencia vacía.
Sintaxis:

IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper)

Where, IntStream is a sequence of primitive 
int-valued elements 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.

Ejemplo 1: función flatMapToInt() con operación de string de análisis a entero.

// Java code for Stream flatMapToInt
// (Function mapper) to get an IntStream
// consisting of the results of replacing
// each element of this stream with the
// contents of a mapped stream.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Strings
        List<String> list = Arrays.asList("1", "2", "3",
                                          "4", "5");
  
        // Using Stream flatMapToInt(Function mapper)
        list.stream().flatMapToInt(num -> IntStream.of(Integer.parseInt(num))).
        forEach(System.out::println);
    }
}

Producción :

1
2
3
4
5

Ejemplo 2: función flatMapToInt() con operación de mapeo de string con su longitud.

// Java code for Stream flatMapToInt
// (Function mapper) to get an IntStream
// consisting of the results of replacing
// each element of this stream with the
// contents of a mapped stream.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a List of Strings
        List<String> list = Arrays.asList("Geeks", "GFG",
                                          "GeeksforGeeks", "gfg");
  
        // Using Stream flatMapToInt(Function mapper)
        // to get length of all strings present in list
        list.stream().flatMapToInt(str -> IntStream.of(str.length())).
        forEach(System.out::println);
    }
}

Producción :

5
3
13
3

Publicación traducida automáticamente

Artículo escrito por Sahil_Bansall y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *