Java 8 Stream

97 阅读1分钟
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

1.空字符串数量

Long count = strings.stream().filter(string->string.isEmpty()).count();

2.筛选后的列表

List<String> filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());

3.合并字符串

String mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));

4.列表

List<Integer> squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());

5.统计

IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();
  • 列表中最大的数:stats.getMax()
  • 列表中最小的数:stats.getMin()
  • 所有数之和:stats.getSum()
  • 平均数:stats.getAverage()