对于Stream流可以拆分为3个步骤
1)创建流:
通过数据源(如:集合、数组)获取流
2)处理流:(中的数据)
对流中的数据进行处理(处理是延迟执行的)
3)收集流:(中的数据)
通过调用收集方法,真正执行处理操作,并产生结果

  1. 创建流
  2. 创建一个流非常简单,有以下几种常用的方式:
  3. 1)Collection的默认方法stream()和parallelStream()
  4. 2)Arrays.stream()
  5. 3)Stream.of()
  6. 4)Stream.iterate()//迭代无限流(1, n->n +1)
  7. 5)Stream.generate()//生成无限流(Math::random)

filter(Predicate p):过滤(根据传入的Lambda返回的ture/false 从流中过滤掉某些数据(筛选出某些数据))
distinct():去重(根据流中数据的 hashCode和 equals去除重复元素)
limit(long n):限定保留n个数据
skip(long n):跳过n个数据

public void test1() throws Exception {
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().limit(2).forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().skip(2).forEach(System.out::println);
}

映射
map(Function f):接收一个函数作为参数,该函数会被应用到流中的每个元素上,并将其映射成一个新的元素。
flatMap(Function mapper):接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

public class Java8Map {
    public static void main(String[] args) {
        System.out.println("=======================map=========================");
        Stream <String> stream = Stream.of("i","love","java");
        stream.map(s -> s.toUpperCase()).forEach(System.out::println);
        System.out.println("=======================flatMap========================");
        Stream<List <String>> stream2 = Stream.of( Arrays.asList("H","E"), Arrays.asList("L", "L", "O"));
        stream2.flatMap(list -> list.stream()).forEach(System.out::println);

    }
}

查找匹配
allMatch:检查是否匹配所有元素
anyMatch:检查是否至少匹配一个元素
noneMatch:检查是否没有匹配的元素
findFirst:返回第一个元素(返回值为Optional)
findAny:返回当前流中的任意元素(一般用于并行流)

  • Optional是Java8新加入的一个容器,这个容器只存1个或0个元素,它用于防止出现NullpointException,它提供如下方法:

  • isPresent()
    判断容器中是否有值。

  • ifPresent(Consume lambda)

容器若不为空则执行括号中的Lambda表达式。

  • T get()

获取容器中的元素,若容器为空则抛出NoSuchElement异常。

  • T orElse(T other)

获取容器中的元素,若容器为空则返回括号中的默认值。

public class Java8Map {
    public static void main(String[] args) {
        System.out.println("======================检查是否匹配所有==========================");
        boolean allMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().allMatch(x-> x>0);
        System.out.println(allMatch);
        System.out.println("======================检查是否至少匹配一个元素====================");
        boolean anyMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().anyMatch(x -> x>7);
        System.out.println(anyMatch);
        System.out.println("======================检查是否没有匹配的元素======================");
        boolean noneMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().noneMatch(x -> x >10);
        System.out.println(noneMatch);
        System.out.println("======================返回第一个元素==========================");
        Optional <Integer> first = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findFirst();
        System.out.println(first.get());
        System.out.println("======================返回当前流中的任意元素=======================");
        Optional<Integer> any = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findAny();
        System.out.println(any.get());
        }
}
  • reduce 将流中的数据结合起来 生成一个新的值
public class Java8Map {
    public static void main(String[] args) {

        System.out.println("=====reduce:将流中元素反复结合起来,得到一个值==========");
        Stream <Integer> stream = Stream.iterate(1, x -> x+1).limit(100);
        //stream.forEach(System.out::println);
        Integer sum = stream.reduce(1,(x,y)-> x+y);
        System.out.println(sum);
    }
}

Collect 操作


public class Java8Map {
    public static void main(String[] args) {
        System.out.println("=====collect:将流转换为其他形式:list");
        List <Integer> list = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toList());
        System.out.println(list);
        System.out.println("=====collect:将流转换为其他形式:set");
        Set<Integer> set = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toSet());
        System.out.println(set);
        System.out.println("=====collect:将流转换为其他形式:TreeSet");
        TreeSet <Integer> treeSet = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect( Collectors.toCollection(TreeSet::new));
        System.out.println(treeSet);
        System.out.println("=====collect:将流转换为其他形式:map");
        Map <Integer, Integer> map = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toMap(Integer::intValue, Integer::intValue));
        System.out.println(map);
        System.out.println("=====collect:将流转换为其他形式:sum");
        Integer sum = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.summingInt(Integer::intValue));
        System.out.println(sum);
        System.out.println("=====collect:将流转换为其他形式:avg");
        Double avg = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.averagingInt(Integer::intValue));
        System.out.println(avg);
        System.out.println("=====collect:将流转换为其他形式:max");
        Optional <Integer> max = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.maxBy(Integer::compareTo));
        System.out.println(max.get());
        System.out.println("=====collect:将流转换为其他形式:min");
        Optional<Integer> min = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.minBy((x,y) -> x-y));
        System.out.println(min.get());   }
}

分组和分区
Collectors.groupingBy()对元素做group操作。
Collectors.partitioningBy()对元素进行二分区操作。

@Before
public void init() {
    products.add(new Product(1L, "苹果手机", 8888.88,"手机"));//注意:要给Product类加一个分类名称dirName字段
    products.add(new Product(2L, "华为手机", 6666.66,"手机"));
    products.add(new Product(3L, "联想笔记本", 7777.77,"电脑"));
    products.add(new Product(4L, "机械键盘", 999.99,"键盘"));
    products.add(new Product(5L, "雷蛇鼠标", 222.22,"鼠标"));
}
@Test
public void test9() throws Exception {
    System.out.println("=======根据商品分类名称进行分组==========================");
    Map<String, List<Product>> map = products.stream().collect(Collectors.groupingBy(Product::getDirName));
    System.out.println(map);
    System.out.println("=======根据商品价格范围多级分组==========================");
    Map<Double, Map<String, List<Product>>> map2 = products.stream().collect(Collectors.groupingBy(
            Product::getPrice, Collectors.groupingBy((p) -> {
                if (p.getPrice() > 1000) {
                    return "高级货";
                    } else {
                        return "便宜货";
                        }
                })));
    System.out.println(map2);

}
@Test
public void test10() throws Exception {
    System.out.println("========根据商品价格是否大于1000进行分区========================");
    Map<Boolean, List<Product>> map = products.stream().collect(Collectors.partitioningBy(p -> p.getPrice() > 1000));
    System.out.println(map);
}

总结

Streamvs Collection
虽然大部分情况下Stream是容器调用Collection.stream()方法得到的,但Stream和Collection有以下不同:

●无存储。Stream不是一种数据结构,它只是某种数据源的一个视图,数据源可以是一个数组,集合等。
●不修改。对Stream的任何修改都不会修改背后的数据源,比如过滤操作并不会删除被过滤的元素,而是产生一个新Stream。
●惰式执行。Stream上的操作并不会立即执行,只有等到用户真正需要结果的时候才会执行。
●可消费性。Stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成。

Stream分类
●中间操作(intermediate operations)
返回值为Stream的大都是中间操作,中间操作支持链式调用,并且会惰式执行

●终端操作(结束操作)(terminal operations)
返回值不为Stream 的为终端操作(立即求值),终端操作不支持链式调用,会触发实际计算

Java8Stream流详解 - 图1