Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created March 18, 2020 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdkosher/147d2500ed40d1dfa9ba798be8f5ab2b to your computer and use it in GitHub Desktop.
Save bdkosher/147d2500ed40d1dfa9ba798be8f5ab2b to your computer and use it in GitHub Desktop.
Sorting on a potentially null field

Say I have a class with a potentially-null field and I want to sort a List of class instances on that field first (nulls last), then fall back on a second non-null field.

@Data
class Foo {
    String bar;
    int baz
}

Given a list of foos called foos and static imports from java.util.Comparator:

   foos.stream()
       .sorted(comparing(Foo::getBar, nullsLast(String::compareTo)).thenComparing(Foo::getBaz))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment