We would like to know how to sort a null list with Optional.ofNullable and ifPresent.
import java.util.Comparator; import java.util.List; import java.util.Optional; //from w ww . j a v a 2s . c om public class Main { public static void main(String... args) { List<String> names3 = null; Optional.ofNullable(names3).ifPresent(list -> list.sort(Comparator.naturalOrder())); System.out.println(names3); } }
The code above generates the following result.