Fork me on GitHub

常用stream函数

本篇记录了常用的stream函数

聚合求和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class demo {
public void test() {
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
Map<String, Object> item1 = new HashMap<String, Object>();
item1.put("key", "wo");
item1.put("price", 1);
items.add(item1);
Map<String, Object> item2 = new HashMap<String, Object>();
item2.put("key", "yuq");
item2.put("price", 2);
items.add(item2);
Map<String, Object> item3 = new HashMap<String, Object>();
item3.put("key", "wo");
item3.put("price", 100);
items.add(item3);
Map<Object, Double> result = items.parallelStream().collect(Collectors.groupingBy(mapper -> {
return mapper.get("key");
}, Collectors.summingDouble(mapper -> {
return ((Integer) mapper.get("price")).doubleValue();
})));
System.out.println(result);
}
}

map

1
2
3
4
5
6
7
public class demo {
public void test() {
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
//省略值
System.out.println(items.stream().map(mapper ->mapper.get("key")).collect(Collectors.toList()));
}
}

reduce

1
2
3
4
5
6
7
8
9
public class demo {
public void test() {
List<Map<String, String>> items = new ArrayList<Map<String, Object>>();
//省略值
System.out.println(items.stream().map(mapper -> {
return mapper.get("key");
}).reduce((accumulator, row) -> accumulator + "," + row).orElse("错误"));
}
}

排序

1
2
3
4
5
6
7
8
9
10
11
public class demo {
public void test() {
List<Map<String, String>> items = new ArrayList<Map<String, Object>>();
//省略值
items.stream().sorted(Comparator.comparing(demo::comparingByPX)).collect(Collectors.toList());
}

public static Integer comparingByPX(Map<String, Object> map) {
return Integer.parseInt(map.get("key").toString());
}
}

过滤

1
2
3
4
5
6
7
public class demo {
public void test() {
List<Map<String, String>> items = new ArrayList<Map<String, Object>>();
//省略值
items.stream().filter(mapper -> "目标值".equals(mapper.get("key"))).collect(Collectors.toList());
}
}

本文标题:常用stream函数

文章作者:啧啧

发布时间:2020年05月20日 - 15:05

最后更新:2020年05月20日 - 15:05

原始链接:http://yoursite.com/2020/05/20/mypage/streams/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------