Reduce to get the longest string

Description

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 {
/*from   w  w w . java  2s .  c  om*/
  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.





















Home »
  Java Streams »
    Examples »




Average
Filter
Group
IntStream
Map
Partition
Reduce
Sort
Sum