Java Stream How to - Get the longest string in Stream








Question

We would like to know how to get the longest string in Stream.

Answer

/*from   ww  w.j  av  a  2 s  . c o  m*/
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Main {
  public static void main(String[] args) {

    List<String> friends = Arrays.asList("CSS", "HTML", "Oracle", "Dart");
    Comparator<String> compByLength = (aName, bName) -> aName.length()
        - bName.length();
    friends
        .stream()
        .max(compByLength)
        .ifPresent(
            longest -> System.out.println("\nThe longest name is " + longest));
  }
}

The code above generates the following result.