Java - Sort string by length, placing null first in Sorted Set

Introduction

If you allow a null element in the SortedSet, you can decide whether the null element will be placed in the beginning or at the end of the Set.

The following code creates a SortedSet using a Comparator that places the null element first:

Demo

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

public class Main {
  public static void main(String[] args) {
    // Sort the names based on their length, placing null first
    SortedSet<String> names = new TreeSet<>(Comparator.nullsFirst(Comparator.comparing(String::length)));
    names.add("Java");
    names.add("XYZ");
    names.add("Python");
    names.add(null); // Adds a null

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

  }//from   w w  w.  j ava  2  s  . co m
}

Result

Related Topic