Sort words by the length (in increasing order) of each word, and then by lexicographical order if they are of the same length. - Java Lambda Stream

Java examples for Lambda Stream:Lambda

Description

Sort words by the length (in increasing order) of each word, and then by lexicographical order if they are of the same length.

Demo Code


import java.util.Collections;
import java.util.List;

public class Main {
  /**//from www.  j  av a  2 s  . co m
   * Sort words by the length (in increasing order) of each word, and then by
   * lexicographical order if they are of the same length.
   * Collections.sort(List<T>, Comparator<? super T>)
   * 
   * @return
   */
  public static List<String> sortWordsByLength(List<String> nWords) {

    Collections.sort(nWords, (o1, o2) -> {
      if (o1.length() == o2.length()) {
        return (o1.compareTo(o2));
      } else {
        return o1.length() - o2.length();
      }
    });

    return nWords;

  }
}

Related Tutorials