? ? ? ? 最近做到一個需求,需要把業(yè)務(wù)側(cè)返回的數(shù)據(jù)(格式為List<JSONObject>),然后根據(jù)前端傳來的排序字段、以及升降序?qū)傩詠砼判虿⒎祷亟o前端。要對List<JSONObject>中的多個屬性字段進(jìn)行動態(tài)的升序或降序排序,我們可以根據(jù)需要使用Comparator.comparing()方法和Comparator.reverseOrder()方法,運用lambda表達(dá)式動態(tài)指定屬性字段和排序順序。以下是自己寫的一個示例代碼,演示了如何實現(xiàn)動態(tài)的降序和升序排序,僅供參考。?? ??
public static void main(String[] args) {
List<JSONObject> jsonList = new ArrayList<>();
// 添加JSONObject對象到List中
JSONObject json1 = new JSONObject();
json1.put("id", 1);
json1.put("name", "Alice");
json1.put("age", 25);
JSONObject json2 = new JSONObject();
json2.put("id", 2);
json2.put("name", "Alice");
json2.put("age", 30);
JSONObject json3 = new JSONObject();
json3.put("id", 3);
json3.put("name", "Bob");
json3.put("age", 20);
jsonList.add(json1);
jsonList.add(json2);
jsonList.add(json3);
List<String> sortProperties = new ArrayList<>();
//動態(tài)指定要排序的屬性字段
//此處可以根據(jù)業(yè)務(wù)需要傳具體字段,此處測試就先寫死
sortProperties.add("name");
sortProperties.add("age");
Map<String,Boolean> sortOrders = new HashMap<>();
//動態(tài)指定屬性字段對應(yīng)的排序順序(true表示降序,false表示升序)
//此處可以根據(jù)業(yè)務(wù)傳具體字段的具體排序方式,此處測試就先寫死
sortOrders.put("name",false);
sortOrders.put("age",true);
// 構(gòu)建Comparator鏈
Comparator<JSONObject> comparator = null;
for (int i = 0; i < sortProperties.size(); i++) {
final int propertyIndex = i;
Comparator<JSONObject> propertyComparator = Comparator.comparing(
(JSONObject o) -> o.getString(sortProperties.get(propertyIndex)),
String.CASE_INSENSITIVE_ORDER
);
if (sortOrders.get(sortProperties.get(propertyIndex))) {
propertyComparator = propertyComparator.reversed();
}
if (comparator == null) {
comparator = propertyComparator;
} else {
comparator = comparator.thenComparing(propertyComparator);
}
}
Collections.sort(jsonList, comparator);
// 輸出排序后的結(jié)果
for (JSONObject json : jsonList) {
System.out.println(json.toString());
}
}
按名字升序,按年齡降序
輸出結(jié)果:
{"name":"Alice","id":2,"age":30}
{"name":"Alice","id":1,"age":25}
{"name":"Bob","id":3,"age":20}
在上述代碼中,首先創(chuàng)建了一個包含多個JSONObject對象的List。然后,使用sortProperties
來動態(tài)指定要排序的屬性字段,使用sortOrders
來動態(tài)指定屬性字段對應(yīng)的排序順序。
在使用for循環(huán)遍歷sortProperties
列表中的屬性字段,并根據(jù)屬性字段在列表中的索引創(chuàng)建一個新的Comparator。在Lambda表達(dá)式中,通過o.get(sortProperties.get(propertyIndex))來獲取屬性字段的值。根據(jù)sortOrders
列表中的值,如果需要降序排序則使用.reversed()方法進(jìn)行反轉(zhuǎn)。
通過循環(huán)構(gòu)建的多個Comparator通過thenComparing方法鏈將它們連接在一起,生成一個能夠?qū)崿F(xiàn)多個屬性字段動態(tài)排序的Comparator。文章來源:http://www.zghlxwxcb.cn/news/detail-609956.html
注意:上述代碼中假設(shè)屬性字段具有相同的類型。如果屬性字段有不同的數(shù)據(jù)類型,可能需要使用適當(dāng)?shù)谋容^器來提取和比較屬性字段的值,即要注意從jsonObject中取對應(yīng)值的時候,是使用getString()還是getInteger()等其它方法。文章來源地址http://www.zghlxwxcb.cn/news/detail-609956.html
到了這里,關(guān)于Java lamda對List<JSONObject>里多個動態(tài)屬性字段進(jìn)行動態(tài)的降序或者升序的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!