java-stream

groupingBy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 List<String> items =
Arrays.asList("apple", "apple", "banana",
"apple", "orange", "banana", "papaya");
Map<String, Long> result =
items.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
System.out.println("result = " + result);
Map<Object, Set<String>> collect = items.stream().collect(Collectors.groupingBy(String::length, Collectors.mapping(e -> e,
Collectors.toSet())));

System.out.println("collect = " + collect);

join

1
String join = items.stream().collect(Collectors.joining(","));

reduce

递归执行所有元素

1
2
3
Stream<Integer> stream = Stream.of(1, 2, 3);
int count = stream.reduce(Integer::sum).orElse(0);
System.out.println("count " + count);

依次与初始值identity进行运算

1
2
3
4
Stream<Integer> stream = Stream.of(2, 0, 3);
int identity = 6
short value = stream.reduce(identity, (a, b) -> a * b).shortValue();
System.out.println("value = " + value);

相当于

1
2
3
4
T result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;

依次与初始值identity进行运算,运行返回其他类型

1
2
3
Stream<Integer> stream = Stream.of(2, 2, 3);
String reduce = stream.reduce("", (a, b) -> a + b, (u, u2) -> "");
System.out.println("reduce = " + reduce);

模拟 join

1
2
3
 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
String join= numbers.stream().map(String::valueOf).reduce((total, element) -> total + element+"").get();
System.out.println("join= " + join);

流快速删除,Collection提供了方法

1
2
List<String> list = new ArrayList<>();
list.removeIf(Predicate<? super E> filter)

Collectors.toMap()问题

Collectors.toMap()要求生成的 map 的 value 不能为 null,否则会报 nullPoint 异常。且 key 不能重复,否则会报 duplicate key 异常