Stream max(Comparator comparator) example

Description

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  w  w . j a  v  a2s .  co  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.





















Home »
  Java Streams »
    Reference »




Collectors
DoubleStream
DoubleStream.Builder
IntStream
IntStream.Builder
LongStream
LongStream.Builder
Stream
Stream.Builder