問題描述:物件集合中,根據物件的某個屬性進行公升降排序時,未考慮對應屬性的null值,導致出現空指標異常。
解決方法:comparator.nullsfirst和comparator.nullslast
listnlist = list.stream().sorted(
comparator.comparing(user::getcode, comparator.nullsfirst(string::compareto)))
.collect(collectors.tolist());
下見原始碼:
/**
* returns a null-friendly comparator that considers to be
* less than non-null. when both are , they are considered
* equal. if both are non-null, the specified is used
* to determine the order. if the specified comparator is ,
* then the returned comparator considers all non-null values to be equal.
** the returned comparator is serializable if the specified comparator
* is serializable.
** @param the type of the elements to be compared
* @param comparator a for comparing non-null values
* @return a comparator that considers to be less than
* non-null, and compares non-null objects with the supplied
* .
* @since 1.8
*/public static comparatornullsfirst(comparator<? super t> comparator)
/*** null-friendly comparators
*/final static class nullcomparatorimplements comparator, serializable
@override
public int compare(t a, t b) else if (b == null) else
}@override
public comparatorthencomparing(comparator<? super t> other)
@override
public comparatorreversed()
}
lambda表示式排序出現空指標
類a的集合alist,需要按a的字段id進行排序 使用lambda表示式進行過濾 排序時,出現了空指標異常 改之前 list alist1 alist.stream distinct sorted comparator.comparing a getid reversed collect colle...
Lambda表示式排序,出現空指標異常
問題描述 物件集合中,根據物件的某個屬性進行公升降排序時,未考慮對應屬性的null值,導致出現空指標異常。解決方法 comparator.nullsfirst和comparator.nullslast listnlist list.stream sorted comparator.comparing...
Lambda表示式排序,解決空指標異常
問題描述 物件集合中,根據物件的某個屬性進行公升降排序時,未考慮對應屬性的null值,導致出現空指標異常。解決方法 第一種 comparator.nullsfirst和comparator.nullslast listrecordlist equipoverrunrecordservice.find...