fork download
  1. import java.util.ArrayList;
  2. import java.util.Comparator;
  3. import java.util.List;
  4.  
  5. class Ideone {
  6.  
  7. public static void main(String[] args) {
  8. final List<BodyOfWater> list = new ArrayList<>(List.of(
  9. BodyOfWater.of(3.0),
  10. BodyOfWater.of(1.0),
  11. BodyOfWater.of(2.0),
  12. BodyOfWater.of(null)));
  13. list.add(null);
  14. list.sort(Comparator.<BodyOfWater>nullsFirst(null).thenComparing(
  15. BodyOfWater::getDepth,
  16. Comparator.<Double>nullsLast(null).thenComparing(d -> d)));
  17. System.out.println(list);
  18. }
  19. }
  20.  
  21. class BodyOfWater {
  22. private final Double depth;
  23.  
  24. private BodyOfWater(Double depth) {
  25. this.depth = depth;
  26. }
  27.  
  28. public static BodyOfWater of(Double depth) {
  29. return new BodyOfWater(depth);
  30. }
  31.  
  32. public Double getDepth() {
  33. return depth;
  34. }
  35.  
  36. @Override
  37. public String toString() {
  38. return "BodyOfWater{" +
  39. "depth=" + depth +
  40. '}';
  41. }
  42. }
Success #stdin #stdout 0.11s 51340KB
stdin
Standard input is empty
stdout
[null, BodyOfWater{depth=1.0}, BodyOfWater{depth=2.0}, BodyOfWater{depth=3.0}, BodyOfWater{depth=null}]