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);

  }//from w  ww .  j  av  a  2 s  . co m
}

Result

Related Topic