-1

Sorting a map <String, Object>

String value can be a Integer, Double or a normal (have to parse String into Integer)

[at a time, all keys will be one data type only]

keys cans be null

nullsLast(comparing(o -> Double.valueOf(o.getKey())));

is throwing NPE.

What to do to make it work?

moovon
  • 2,219
  • 1
  • 17
  • 15

1 Answers1

2

It's not nullsLast which is throwing the NullPointerException, but the Double.valueOf(String) method.

You can handle this by checking for nulls explicitly.

The second problem is that comparing doesn't support null values. What you want to do is compare the object by their key (parsed as Double), using the nullsLast comparator to compare the keys:

comparing(o -> o.getKey() == null ? null : Double.valueOf(o.getKey()), nullsLast(Comparator.naturalOrder()));
Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • ``` public static > Comparator comparing( Function super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); } ``` it's failing with NPE inside the comparing function – moovon Dec 07 '21 at 06:36
  • @moovon Yes, I shouldn't post code without trying it out myself... – Hoopje Dec 09 '21 at 08:34