Java8 Stream 常用代码

Stream

基于java8的流写业务逻辑,可以用精简的代码实现复杂的业务逻辑。取代以前复杂的多重for循环代码。

:: 关键字

为了使得代码更为直观

1
2
3
num -> Integer::valueOf;
等价于
Integer.valueOf(num)

过滤

首先使用for循环方案。

1
2
3
4
5
6
7
8
9
public List<Item> getItems() {
List<Items> result = new ArrayList<>();
for (Items item : items) {
if (item.getTag().equals("Java")) {
result.add(item);
}
}
return result;
}

使用Stream操作的方案。
过程:List -> Filter -> List

1
2
3
4
5
public List<Item> getItems() {
return items.stream()
.filter(item -> item.getTag().equals("Java"))
.collect(Collectors.toList());
}

分组

过程:List -> Stream -> Map<String, ?>

1
2
3
4
public Map<String, List<Item>> groupByTag() {
return items.stream()
.collect(Collectors.groupingBy(Item::getTag));
}

排序

1
2
3
Collections.sort(items, (String a, String b) -> b.compareTo(a));
// 简写
Collections.sort(items, (a, b) -> b.compareTo(a));

List<?>转为List<?>(获取每个List对象中的属性)

过程:List< Item> -> stream -> List< String>

1
items.stream().map(Item::getTag).collect(Collectors.toList());

list转为String(获取每个List对象中的属性,逗号分隔组成的字符串)

过程:List<?> -> stream -> String

1
2

items.stream().map(Item::getTag).collect(Collectors.joining(","));

list统计总数

过程:List<?> -> stream -> long

1
2

items.stream().count();

list转为map

过程:List<?> -> stream -> Map<String, ?>

1
2
3
4
5
6
7
return items.stream().collect(Collectors.toMap(Item::getId, item -> item));
// 使用Function接口中的一个默认方法代替,使整个方法更简洁优雅:
return items.stream().collect(Collectors.toMap(Item::getId, Function.identity()));
// 重复key的情况 这个方法可能报错(java.lang.IllegalStateException: Duplicate key)
reuturn items.stream().collect(Collectors.toMap(Item::getTag, Function.identity()));
// 使用后者覆盖前者来解决key重复问题。
return items.stream().collect(Collectors.toMap(Item::getTag, Function.identity(), (key1, key2) -> key2));

循环1到10

1
2

IntStream.range(0, 10).forEach((index) -> { });

reduce

具体用法参考这里
计算总金额

1
2

BigDecimal sum = items.stream().map(Item::getPrice).reduce(BigDecimal::add).get();

reduce默认返回的是Optional类型,
使用初始值的reduce,因为提供了初始值,所以返回值不再是Optional

1
2

.reduce(0, (a, b) -> a + b);

reduce高级用法代码比较难看,其实可以使用.map + 简单的reduce替代

Array 转 Stream

Array和Map是没有流方法(.stream())的,但是

1
2

Arrays.stream(results)

Map 转 Stream

Array和Map是没有流方法(.stream())的,但是

1
2
3
4

itemsMap.entrySet().stream()
itemsMap.keySet().stream()
itemsMap.valueSet().stream()

过滤Map

过程:Map -> Stream -> Filter -> String

1
2
3
4
5

result = itemsMap.entrySet().stream()
.filter(map -> "aws.amazon.com".equals(map.getValue()))
.map(map -> map.getValue())
.collect(Collectors.joining());