Java Stream How to - Reduce to get the longest string








The following code shows how to reduce to get the longest string.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Main {
/*  ww  w. j  av  a  2  s  . c o m*/
  public static void main(String[] args) {
    List<String> names = Arrays.asList("XML", "HTML", "CSS", "Javascript", "Java", "Static");

    Optional<String> longestName = 
       names.stream()
            .reduce((name1,name2)->name1.length() >= name2.length() ? name1 : name2);

    if (longestName.isPresent()) {
        System.out.println(longestName.get());
    } else {
        System.out.println("WTF?");
    }

  }
}

The code above generates the following result.