Java - Sort list in ascending order by element's length using sort() method from List interface

Description

Sort list in ascending order by element's length using sort() method from List interface

Demo

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("XML");
    list.add("Javascript");
    list.add("Json");
    list.add("Java");

    System.out.println("List: " + list);

    // Uses List.sort() method with a Comparator
    list.sort(Comparator.comparing(String::length));

    System.out.println("Sorted List: " + list);
  }//from   w w w  .j  av  a2 s. c o m
}

Result

Related Topic