Java Stream How to - Sort String Stream with Method reference








Question

We would like to know how to sort String Stream with Method reference.

Answer

//from   w  ww  .  j a  va2 s  . co  m
import java.util.Arrays;
import java.util.List;

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

    List<String> friends = Arrays.asList("CSS", "HTML", "Oracle", "Dart");

    //just sort using lambda comparator
    System.out.println("sort:");

    friends.stream().sorted(String::compareTo)
            .forEach(System.out::println);
  }
}

The code above generates the following result.