Java - Sort the string based on their length using Sorted Set

Description

Sort the string based on their length using Sorted Set

Demo

import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    SortedSet<String> names = new TreeSet<>(Comparator.comparing(String::length));
    names.add("Java");
    names.add("aaa");
    names.add("Python");
    names.add("AAA"); // A duplicate that is ignored

    // Print the sorted names
    names.forEach(System.out::println);

  }/*  ww w .j a  v  a2 s .  c  o m*/
}

Result

Related Topic