Java8出现的API大大简化了集合操作:
List<String> strings = List.of("abc", "bc", "efg", "gg", "abcd", "jkl");
//集合中空字符串个数
System.out.println(strings.parallelStream().filter(String::isEmpty).count());
//去掉空字符串
List<String> newStrings = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
//限制输出个数
newStrings.stream().limit(3).forEach(System.out::println);
System.out.println();
//排序
newStrings.stream().sorted().forEach(System.out::println);
System.out.println();
//集合元素合并成字符串
System.out.println(newStrings.stream().collect(Collectors.joining(",")));
List<Integer> ints = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
IntSummaryStatistics statistics = ints.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("max:" + statistics.getMax());
System.out.println("min:" + statistics.getMin());
System.out.println("sum:" + statistics.getSum());
System.out.println("average:" + statistics.getAverage());
System.out.println("count:" + statistics.getCount());
结果如下:
0
abc
bc
efg
abc
abcd
bc
efg
gg
jkl
abc,bc,efg,gg,abcd,jkl
max:10
min:1
sum:55
average:5.5
count:10
到了Java9之后,增加了如下方法:
List<String> strings = List.of("abc", "bc", "efg", "gg", "abcd", "jkl");
//输出集合元素直到遇到不符合条件的字符串
strings.stream().takeWhile(s -> !s.equals("gg")).forEach(System.out::println);
System.out.println();
//从不符合条件的字符串开始输出集合元素
strings.stream().dropWhile(s -> !s.equals("gg")).forEach(System.out::println);
//指定初始值创建顺序流,设置停止条件与每次迭代的操作
IntStream.iterate(0, x -> x <= 10, x -> x + 2).forEach(System.out::println);
结果如下:
abc
bc
efg
gg
abcd
jkl
0
2
4
6
8
10