Java Streams - Stream max(Comparator comparator) example








Stream max(Comparator<? super T> comparator) returns the maximum element of this stream according to the provided Comparator.

Syntax

max has the following syntax.

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

Example

The following example shows how to use max.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/*from   w ww. jav  a2  s. c o m*/
public class Main {
  public static void main(String[] args) {
    List<String> stringList = Arrays.asList("2","1","3","4");

    Optional<String> m = stringList
              .stream()    
              .max(Comparator.reverseOrder());
    if(m.isPresent()){
      System.out.println(m.get());  
    }else{
      System.out.println("No Value");
    }
    
  }
}

The code above generates the following result.