简体   繁体   中英

How do I avoid NullPointerExceptions in lambda comparators?

I want to compare two given objects which might be null at runtime. In my example:

@Test
public void shouldCompareAgents() {

    Agent a1 = new Agent();
    a1.setId("4711");
    a1.setType(null);

    Agent a2 = new Agent();
    a2.setId(a1.getId());
    a2.setType(a1.getType());

    assertEquals("Agent.getId", 0,
            Comparator.comparing(Agent::getId).compare(a1, a2));

    assertEquals("Agent.getType", 0,
            Comparator.comparing(Agent::getType).compare(a1, a2));
}

The assertion by id works fine, by type does not as a1.getType() is null. Is there a way to avoid this? I tried Comparator.nullsLast(...) , but that makes no sense as I am not sorting elements here.

I have lots of assertions to do, so I'd prefer "a one-liner" . I am new to lambda expressions.

If you just want to use this in a JUnit test, why don't you just pass the objects you want to compare directly to the assertEquals method?

assertEquals("Agent.getId", a1.getId(), a2.getId());

This also helps JUnit to generate a useful error message when the test fails.

If you want to do this in production code, you can use Objects.equals :

if (Objects.equals(a1.getId(), a2.getId())) { ... }

which is present since Java 7.

Something like this:

Comparator.comparing(Agent::getType, 
    Comparator.nullsLast(Comparator.naturalOrder()))

Since you need this to be used in more places, you can extract it as :

    private static <R, T extends Comparable<T>> boolean areEqual(R left, R right, Function<R, T> function) {
         return Comparator.comparing(
                 function, 
                 Comparator.nullsLast(Comparator.naturalOrder())) 
                           .compare(left, right) == 0;
}

You can use Objects.equals :

assertEquals("Agent.getId", true,
    Objects.equals(a1.getID(),a2.getID());

assertEquals("Agent.getType", true,
    Objects.equals(a1.getType(),a2.getType());

Objects.equals handles null s for you.

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