java stream api介绍

简介

Stream API借助前面介绍的java lambda表达式来进行集合数据处理。
下面举些常用的例子来熟悉下。

forEach

stream方法不调用也可以使用forEach

Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 4.3, 5.4 }).forEach(System.out::println);

filter

集合内数据过滤

Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 4.3, 5.4 }).stream().filter(x -> x > 3.0).forEach(System.out::println);

map

从原数据(list, set)生成新数据(list, set)

Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 4.3, 5.4 }).stream().map(x -> x * x).forEach(System.out::println);

collect

用collect取代for这样的语法
collect(supplier(for循环外部的变量), accumulator(for循环内部处理), combiner(并行处理时,supplier汇总处理))

Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 4.3, 5.4 }).stream().collect(HashMap::new, (map, x) -> map.put(x, x * x), (map1, map2) -> map1.forEach(map2::put)).entrySet().forEach(System.out::println);

使用collectors

Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 1.0, 5.4 }).stream().collect(Collectors.toSet()).forEach(System.out::println);

mapTo[*]等

使用mapTo[数值类型]流,求最小,最大,平均数

Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 4.3, 5.4 }).stream().mapToDouble(x -> x).average().ifPresent(System.out::println)

求标准方差

标准方差公式

List<Double> sample = Arrays.asList(new Double[] { 1.0, 2.1, 3.2, 4.3, 5.4 });
double mu = sample.stream().mapToDouble(x -> x).average().getAsDouble();
double siguma = Math.sqrt(sample.stream().map(x -> Math.pow(x - mu, 2.0)).mapToDouble(x -> x).average().getAsDouble());
System.out.println(siguma);

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注