Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
stream
min
communitycreator

What is the Stream min() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Stream min() method will return an Optional that contains the smallest value of the stream. The smallest values are evaluated based on the passed Comparator argument.

  • If the stream is empty, then an empty Optional is returned.
  • If the minimum value is null, then NullPointerException is thrown.
  • The min method is a terminal operationThe stream cannot be used after this is called..

Example

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, -10);
Optional<Integer> min;
min = list
.stream()
.min((a, b) -> a -b );
System.out.println("The list is " + list);
System.out.println("Minumum value of the list is " + min.get());
}
}

In the above code, we have used the Stream min() method on the list stream by passing a comparator to get the minimum value of the list. The minimum value can be retrived from the list by calling the get method of the returned Optional.

Calling min on empty stream

If the stream is empty, then an empty Optional is returned.

import java.util.List;
import java.util.ArrayList;
import java.util.Optional;
public class Main {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
Optional<Integer> min;
min = list
.stream()
.min((a, b) -> a -b );
System.out.println("The list is " + list);
System.out.println("Checking if the value present in the Optional - " + min.isPresent());
}
}

RELATED TAGS

java
stream
min
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring