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);
  }//  w w  w . ja  va 2s .  co m
}

Result

Related Topic