use*_*980 2 java sorting null comparator
我需要显示一个帐户对象列表,并在其中一个帐户对象字段(所有字符串类型)上进行排序。但是,某些帐户字段值未null显示在中JSON。null pointer exception当我对那些缺失的字段进行排序时,它给了我一个机会。如何Comparator在排序期间忽略忽略的字段?
我试过了,Comparator.comparing()但它仅适用于公共字段(所有帐户对象中都存在)。如果我尝试对帐户对象之一中缺少的字段进行排序。NullPointerException发生了。当然,如果我试图强制所有字段以空字符串值(“”)的形式显示,那么它可以正常工作,但看起来不太好,因为这些字段可能太多。
帐户定义
@JsonInclude(Include.NON_NULL)
private String type;
@JsonInclude(Include.NON_NULL)
private String accountNumber;
@JsonInclude(Include.NON_NULL)
private String accountStatus;
@JsonInclude(Include.NON_NULL)
private String accountValue;
....
Run Code Online (Sandbox Code Playgroud)
排序以下列表-仅type和accountNumber是通用的
"accounts": [
{
"type": "type1",
"accountNumber": "1816227",
"accountStatus": "cancelled",
},
{
"type": "type2",
"accountNumber": "2816218",
"accountValue": "19438.60",
},
{
"type": "type3",
"accountNumber": "2209890",
"accountStatus": "inactive",
"accountValue": "4343.410",
}
Run Code Online (Sandbox Code Playgroud)
if (sortField.equalsIgnoreCase("type")) {
accountComparator = Comparator.comparing(Accounts::getType);
}else if(sortField.equalsIgnoreCase("accountNumber")) {
accountComparator = Comparator.comparing(Accounts::getAccountNumber);
}else if(sortField.equalsIgnoreCase("accountStatus")) {
accountComparator = Comparator.comparing(Accounts::getAccountStatus);
}else if(sortField.equalsIgnoreCase("accountValue")) {
accountComparator = Comparator.comparingDouble(acc ->
Double.valueOf(acc.getAccountValue()));
}
......
Run Code Online (Sandbox Code Playgroud)
Nullpointer exception在以下一行上的行Sort上accountStatus,
accountValue其中一个帐户缺少。
totalAcctList.sort(accountComparator.reversed());
如前所述,如果我显示所有帐户accountStatus,
accountValue例如“ accountStatus”:“”,"accountValue":"0.0"那么它将起作用。
您可以决定将所有nulls放在列表的开头或结尾,然后分别使用Comparator.nullsFirst或Comparator.nullsLast:
else if (sortField.equalsIgnoreCase("accountStatus")) {
accountComparator =
Comparator.comparing(Accounts::getAccountStatus,
Comparator.nullsLast(Comparator.naturalOrder()));
}
Run Code Online (Sandbox Code Playgroud)
编辑:
因为accountValue您可以采用类似的方法,尽管由于原语doubles不能为null,所以在尝试解析之前,您必须先处理它们:
else if (sortField.equalsIgnoreCase("accountValue")) {
accountComparator =
Comparator.comparing((Account a) -> a.getAccountValue() == null)
.thenComparingDouble((Account a) ->
Double.parseDouble(a.getAccountValue()));
}
Run Code Online (Sandbox Code Playgroud)