我想比较两个在运行时可能为null的给定对象.在我的例子中:
@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));
}
Run Code Online (Sandbox Code Playgroud)
id的断言工作正常,按类型不是a1.getType()null.有办法避免这种情况吗?我尝试过Comparator.nullsLast(...),但这没有任何意义,因为我没有在这里排序元素.
我有很多断言要做,所以我更喜欢"单行".我是lambda表达式的新手.