简体   繁体   中英

Java Collections max NullPointerException

I have java 1.8.0_171 and the following code in DataUtils.java class:

List<BigDecimal> list = new ArrayList<>();
list.add(new BigDecimal(0));
list.add(new BigDecimal(-2));
list.add(new BigDecimal(10));
list.add(new BigDecimal(200));

if ((Collections.max(list).subtract(Collections.min(list)).compareTo(new BigDecimal(0)) != 0)) {
    .....
            } 

And I have the following exception:

Exception in thread "main" java.lang.NullPointerException at java.util.Collections.max(Unknown Source) at com.util.DataUtils.calculateRetsentindex(DataUtils.java:23)

The default jdk is set on Eclipse correctly, clean-rebuild don't fix. Please, advice

This means that in your collection you probably have added a null element. In your example:

 List<BigDecimal> list = new ArrayList<>();
          list.add(new BigDecimal(0));
          list.add(new BigDecimal(-2));
          list.add(new BigDecimal(10));
          list.add(new BigDecimal(200));
          if ((Collections.max(list).subtract(Collections.min(list)).compareTo(new BigDecimal(0)) != 0)) {
                System.out.println("OK");
          } 

It prints "OK" properly. If you change the first object to null though:

list.add(null);

You get similar exception to yours.

And if you do Collections.max(null); you get the exact same exception. So I guess your list is not initialized when you do the call.

Filter null elements out, before ::max them:

import static java.util.Comparator.naturalOrder;
...

  list.stream()
      .filter(Objects::nonNull)
      .max(naturalOrder())
      .orElse(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM