java 8 stream 流操作list (不斷更新
阿新 • • 發佈:2019-01-02
最近stream操作list用的特別爽,但是網上介紹複雜點的流操作並沒有太多資料,介於我稍有研究,想把一些流的操作記錄一下,以後參考
1,對list進行多key排序
list = list.stream().sorted(
Comparator.comparing(StreamService :: comparingByKey1)
.thenComparing(StreamService:: comparingByKey2)
.thenComparing(StreamService:: comparingByKey3)
.thenComparing(StreamService:: comparingByKey4)
.thenComparing(StreamService:: comparingByKey5)).collect(Collectors.toList());
StreamService 裡需要宣告的方法
private static String comparingByKey1(Map<String, Object> map){ return (String) map.get("Key1"); } private static String comparingByKey2(Map<String, Object> map){ return (String) map.get("Key2");
}
private static String comparingByKey3(Map<String, Object> map){ return map.get("Key3").toString(); } private static String comparingByKey4(Map<String, Object> map){ return map.get("Key4").toString(); } private static String comparingByKey5(Map<String, Object> map){ return map.get("Key5").toString(); }這樣,list會從key1 - key5依次升序排序,
2 .list多項分組併合計某項
list = list.stream().collect(
Collectors.groupingBy(d -> String.format("%s||%s||%s||%s||%s", d.get("key1"), d.get("key2") , d.get("key3"),
d.get("key4") , d.get("key5")) ,
Collectors.summingDouble(d -> Double.parseDouble((String)d.get("quantity")))
)).entrySet().stream().map(entry -> {
Map<String, Object> map = new HashMap<String, Object>();
String[] keys = entry.getKey().split("\\|\\|");
map.put("1", keys[0]);
map.put("2", keys[1]);
map.put("3", keys[2]);
map.put("4", keys[3]);
map.put("5", keys[4]);
map.put("6", entry.getValue());
return map;
}).collect(Collectors.toList());
這樣操作,會先把list 按key1 - key5分組併合計quantity
最終整合list 輸出 list
1= key1
2= key2
3= key3
...
來獲取到一個新的list