java8新特性Stream用法详解

1、Stream的使用场景。

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一 个则是 Stream API(java.util.stream.*)。

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对

Stream API 提供了一种高效且易于使用的处理数据的方式。

2、Stream三个操作步骤

创建 Stream

一个数据源(如:集合、数组),获取一个流  中间操作

一个中间操作链,对数据源的数据进行处理  终止操作(终端操作)

一个终止操作,执行中间操作链,并产生结果。

3、创建Stream

public static<T> Stream<T> of(T... values) : 返回一个流

static <T> Stream<T> stream(T[] array): 返回一个流

4、Stream的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水 线上触发终止操作,否则中间操作不会执行任何的处理! 而在终止操作时一次性全部处理,称为“惰性求值”。

filter(Predicate p) 接收 Lambda , 从流中排除某些元素。

distinct() 筛选,通过流所生成元素的 hashCode() 和 equals() 去 除重复元素 limit(long maxSize) 截断流,使其元素不超过给定数量。

skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素 不足 n 个,则返回一个空流。与 limit(n) 互补

map(Function f) 接收一个函数作为参数,该函数会被应用到每个元 素上,并将其映射成一个新的元素。

mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 DoubleStream。 mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元 素 上,产生一个新的 IntStream。

mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 LongStream。

flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另 一个流,然后把所有流连接成一个流

sorted() 产生一个新流,其中按自然顺序排序

sorted(Comparator comp) 产生一个新流,其中按比较器顺序排序。

5、Stream终止操作

allMatch(Predicate p) 检查是否匹配所有元素

anyMatch(Predicate p) 检查是否至少匹配一个元素

noneMatch(Predicate p) 检查是否没有匹配所有元素

findFirst() 返回第一个元素

终端操作会从流的流水线生成结果。其结果可以是任何不是流的 值,例如:List、Integer,甚至是 void 。

findAny() 返回当前流中的任意元素

count() 返回流中元素总数

max(Comparator c) 返回流中最大值

min(Comparator c) 返回流中最小值

reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。 返回 T 归约 reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。 返回 Optional<T> 备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它 来进行网络搜索而出名。

forEach(Consumer c)

collect(Collector c) 将流转换为其他形式。接收一个 Collector接口的 实现,用于给Stream中元素做汇总的方法

toList List<T> 把流中元素收集到List

List<Employee> emps= list.stream().collect(Collectors.toList()); toSet Set<T> 把流中元素收集到Set

Set<Employee> emps= list.stream().collect(Collectors.toSet()); toCollection Collection<T> 把流中元素收集到创建的集合

Collection<Employee>emps=list.stream().collect(Collectors.toCollection(ArrayList::new)); counting Long 计算流中元素的个数

long count = list.stream().collect(Collectors.counting()); summingInt Integer 对流中元素的整数属性求和

inttotal=list.stream().collect(Collectors.summingInt(Employee::getSalary)); averagingInt Double 计算流中元素Integer属性的平均 值 doubleavg= list.stream().collect(Collectors.averagingInt(Employee::getSalary)); summarizingInt IntSummaryStatistics 收集流中Integer属性的统计值。 如:平均值

sum = (int) sumResults.stream().collect(Collectors.summarizingInt(QuestionDetailVo::getScore)).getSum();
List<HzbCompanyEnergy> list = hzbCompanyEnergyService.list();
List<HzbCompanyEnergy> energyConsumptions = list.stream().filter(data -> data.getYear().equals(String.valueOf(year))).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(energyConsumptions)) {
Double totalWaterConsumption = energyConsumptions.stream().map(o -> o.getTotalWaterConsumption()).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
Double totalPowerConsumption = energyConsumptions.stream().map(o -> o.getTotalPowerConsumption()).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
Double totalHeatConsumption = energyConsumptions.stream().map(o -> o.getTotalHeatConsumption()).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
Double totalAirConsumption = energyConsumptions.stream().map(o -> o.getTotalAirConsumption()).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
parkEnergy.setAirConsumption(String.valueOf(totalAirConsumption)).setHeatConsumption(String.valueOf(totalHeatConsumption))
.setPowerConsumption(String.valueOf(totalPowerConsumption)).setWaterConsumption(String.valueOf(totalWaterConsumption));
}