0

I have the following code given below :

final LinkedHashMap<String, Integer> linkedHashMapCounterMap = new LinkedHashMap<>(); 
linkedHashMapCounterMap.put("abc", 2); 
linkedHashMapCounterMap.put("xyz", 5); 
final String maxColln = Collections.max(
            linkedHashMapCounterMap.entrySet(),
            (entry1, entry2) -> entry1.getValue().intValue() - 
                                entry2.getValue().intValue())
     .getKey();

After running the code, I'm getting this exception :

java.util.NoSuchElementException: null at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:721) ~[?:1.8.0_202] at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:752) ~[?:1.8.0_202] at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:750) ~[?:1.8.0_202] at java.util.Collections.max(Collections.java:708) ~[?:1.8.0_202]

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    It works with me in Java-8 and Java-13, can you please show us what are your imports? also which version of Java you are using? – Youcef LAIDANI Jan 25 '20 at 16:04

1 Answers1

1

There is an edge-case bug in the comparator lambda, but that shouldn't cause an NPE. (Use Integer.compareTo(Integer): see Java Integer compareTo() - why use comparison vs. subtraction?)

I think that the NPE must be due to a threading bug; e.g. there is another thread modifying the map while this code is running. I cannot see how this code could NPE in next(), in any other way.

Either way, we need a minimal reproducible example to take this any further.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216