根据Java集合对象中的一个字段对其进行排序并应用检查


retList.sort((comp1, comp2) ->
compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment())));

我想在比较之前添加一个空检查。我该怎么做?

retList.sort((comp1, comp2) ->
if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment()));
);
//I want to do something like this

您的操作

retList.sort((comp1, comp2) ->
compartmentOrderMap.get(comp2.getCompartment())
.compareTo(compartmentOrderMap.get(comp1.getCompartment())));

相当于

retList.sort(Comparator.comparing(
c -> compartmentOrderMap.get(c.getCompartment()), 
Comparator.reverseOrder()));

有了这种基于工厂的形式,您可以很容易地将值比较器替换为零安全变体,例如

retList.sort(Comparator.comparing(
c -> compartmentOrderMap.get(c.getCompartment()),
Comparator.nullsFirst(Comparator.reverseOrder())));

你必须决定一项政策。您也可以使用nullsLast来代替nullsFirst

对于多行代码,您必须将{}放入lambda中:

retList.sort((comp1, comp2) -> {
if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
return compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment()));
else 
// throw a RuntimeException or return some integer value based on your logic
});

使用if/then/else指定您的需求。如果您希望所有这些都在一行中,请检查上的三元运算符https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

这里的解释包括一些例子:https://www.tutorialspoint.com/Java-Ternary-Operator-Examples

相关内容

  • 没有找到相关文章

最新更新