Java Stream get max value

Description

Java Stream get max value



import java.util.ArrayList;
import java.util.Optional;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {

    // Create a list of Integer values.
    ArrayList<Integer> myList = new ArrayList<>();
    myList.add(7);/* w  ww. j a  v a2  s  . co  m*/
    myList.add(8);
    myList.add(1);
    myList.add(2);
    myList.add(7);
    myList.add(5);

    System.out.println("Original list: " + myList);

     Stream<Integer> myStream = myList.stream();

     Optional<Integer> minVal = myStream.min(Integer::compare);
    if (minVal.isPresent())
      System.out.println("Minimum value: " + minVal.get());

    // Must obtain a new stream because previous call to min()
    // is a terminal operation that consumed the stream.
    myStream = myList.stream();
    Optional<Integer> maxVal = myStream.max(Integer::compare);
    if (maxVal.isPresent())
      System.out.println("Maximum value: " + maxVal.get());
  }
}



PreviousNext

Related