Stream flatMapToLong() en Java con ejemplos

Stream flatMapToLong (Mapeador de funciones) aplica la función de mapeador dada a cada elemento de una secuencia y devuelve un LongStream. Stream flatMapToLong (Mapeador de funciones) es una operación intermedia . 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:

LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper)

Where, LongStream is a sequence of primitive
long-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: flatMapToLong() con operación de string de análisis a largo.

// Java code for Stream flatMapToLong
// (Function mapper) to get an LongStream
// 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.LongStream;
  
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 flatMapToLong(Function mapper)
        list.stream().flatMapToLong(num -> 
                     LongStream.of(Long.parseLong(num))).
                            forEach(System.out::println);
    }
}

Producción :

1
2
3
4
5

Ejemplo 2: flatMapToLong() con operación de string de mapeo con longitud de string.

// Java code for Stream flatMapToLong
// (Function mapper) to get an LongStream
// 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.LongStream;
  
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 flatMapToLong(Function mapper)
        // to get length of all strings present in list
        list.stream().flatMapToLong(str -> 
                        LongStream.of(str.length())).
                        forEach(System.out::println);
    }
}

Producción :

5
3
13
3

Ejemplo 3: función flatMapToLong() con operación de flujo de retorno.

// Java code for Stream mapToLong
// (ToLongFunction mapper) to get a
// LongStream by applying the given function
// to the elements of this stream.
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating a list of Strings
        List<String> list = Arrays.asList("5.36","27.9",
                                         "3","4.2","5");
  
        // Using Stream mapToLong(ToLongFunction mapper)
        // and displaying the corresponding LongStream
        list.stream().flatMapToLong(n
                     -> LongStream.of(Long.parseLong(n)) )
                     .forEach(System.out::println);
    }
}

Producción :

Exception in thread "main" java.lang.NumberFormatException: For input string: "5.36"

Nota: una excepción Java NumberFormatException generalmente ocurre cuando intenta hacer algo como convertir una string en un valor numérico, como int, float, double, long, etc.

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 *