Método Stream min() en Java con ejemplos

Stream.min() devuelve el elemento mínimo de la secuencia según el comparador proporcionado. Un Comparador es una función de comparación, que impone un ordenamiento total en una colección de objetos. min() es una operación de terminal que combina elementos de flujo y devuelve un resultado resumido. Entonces, min() es un caso especial de reducción. El método devuelve una instancia opcional.

Sintaxis:

Optional<T> min(Comparator<? super T> comparator)

Where, Optional is a container object which
may or may not contain a non-null value 
and T is the type of objects
that may be compared by this comparator

Excepción: este método lanza NullPointerException si el elemento mínimo es nulo.

Ejemplo 1: mínimo de la lista de enteros.

// Java code for Stream.min() method to get
// the minimum element of the Stream
// according to the provided Comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of integers
        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
  
        // Using stream.min() to get minimum
        // element according to provided Integer Comparator
        Integer var = list.stream().min(Integer::compare).get();
  
        System.out.print(var);
    }
}

Producción :

-18

Ejemplo 2: Comparador inverso para obtener el valor máximo usando la función min().

// Java code for Stream.min() method
// to get the minimum element of the 
// Stream according to provided comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of integers
        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
  
        // Using Stream.min() with reverse
        // comparator to get maximum element.
        Optional<Integer> var = list.stream()
                    .min(Comparator.reverseOrder());
  
        // IF var is empty, then output will be Optional.empty
        // else value in var is printed.
        if(var.isPresent()){
        System.out.println(var.get());
        }
        else{
            System.out.println("NULL");
        }
          
    }
}

Producción :

25

Ejemplo 3: comparación de strings en función de los últimos caracteres.

// Java code for Stream.min() method
// to get the minimum element of the 
// Stream according to provided comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating an array of strings
        String[] array = { "Geeks", "for", "GeeksforGeeks",
                           "GeeksQuiz" };
  
        // The Comparator compares the strings
        // based on their last characters and returns
        // the minimum value accordingly.
        Optional<String> MIN = Arrays.stream(array).min((str1, str2) -> 
                    Character.compare(str1.charAt(str1.length() - 1), 
                                      str2.charAt(str2.length() - 1)));
  
        // If a value is present,
        // isPresent() will return true
        if (MIN.isPresent()) 
            System.out.println(MIN.get()); 
        else
            System.out.println("-1"); 
    }
}

Producción :

for

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 *