Java8 Stream流方法

Stream流的简介:

Stream流是Java8 API的新成员,它允许以声明性方式处理数据集合(通过查询语句来表达,而不是临时编写一个实现)。

就现在来说,可以把它们看成遍历数据集的高级迭代器。此外,流还可以透明地并行处理,无需写任何多线程代码了!

Stream流的方法:

Stream流的方法
流方法官方解释示例白话文解释+运行结果
filter(中间操作)该操作会接受一个谓词(一个返回boolean的函数)作为参数,并返回一个包括所有符合谓词的元素的流。

List<Dish> vegetarianMenu = menu.stream()

.filter(Dish::isVegetarian)

.collect(toList());

System.out.println(vegetarianMenu);

为true的返回

运行结果:

[french fries, rice, season fruit, pizza]

distinct

(中间操作)返回一个元素各异(根据流所生成元素的hashCode和equals方法实现)的流。

List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 3, 2, 4);

numbers.stream()

.filter(i -> i % 2 == 0)

.distinct()

.forEach(System.out::println);

distinct()是去重

运行结果:

2
4

limit

(中间操作)会返回一个不超过给定长度的流。

List<Dish> dishes = menu.stream()

.filter(d -> d.getCalories() > 300)

.limit(3)

.collect(toList());

System.out.println(dishes);

主要返回的是长度,只有大于300的字段才能被显示

运行结果:

[pork, beef, chicken]

skip

(中间操作)返回一个扔掉了前n个元素的流

 

List<Dish> dishes = menu.stream()

.filter(d -> d.getCalories() > 300)

.skip(2)

.collect(toList());

System.out.println(dishes);

skip(2)代表不要前两个元素

运行结果:

[chicken, french fries, rice, pizza, prawns, salmon]

map(中间操作)接受一个函数作为参数。这个函数会被应用到每个元素上,并将其映射成一个新的元素(使用映射一词,是因为它和转换类似,但其中的细微差别在于它是“创建一个新版本”而不是去“修改”)。

List<String> dishNames = menu.stream()

.map(Dish::getName)

.collect(toList());

System.out.println(dishNames);

只返回name属性

运行结果:

[pork, beef, chicken, french fries, rice, season fruit, pizza, prawns, salmon]

flatMap(中间操作)使用flatMap方法的效果是,各个数组并不是分别映射成一个流,而是映射成流的内容。所有使用map(Arrays::stream)时生成的单个流都被合并起来,即扁平化为一个流。

List<String> words = Arrays.asList("Goodbye", "World");

List<String> uniqueCharacters = words.stream()

.map(w -> w.split(""))

.flatMap(Arrays::stream)

.distinct()

.collect(Collectors.toList());

System.out.println(uniqueCharacters);

把Arrays的元素,变成

运行结果:

[G, o, d, b, y, e, W, r, l]

sorted(中间操作)返回排序后的流

List<String> traderStr = menu.stream()

.map(transaction -> transaction.getName())

.sorted()

.collect(toList());

System.out.println(traderStr);

运行结果:

[beef, chicken, french fries, pizza, pork, prawns, rice, salmon, season fruit]

anyMatch(终端操作)可以回答“流中是否有一个元素能匹配给定的谓词”。

if (menu.stream().anyMatch(Dish::isVegetarian)) {

System.out.println("The menu is (somewhat) vegetarian friendly!!");

}

判断的条件里,任意一个元素成功,返回true
allMatch(终端操作)会看看流中的元素是否都能匹配给定的谓词。

boolean isHealthy = menu.stream()

.allMatch(d -> d.getCalories() < 1000);

System.out.println(isHealthy);

判断条件里的元素,所有的都是,返回true
noneMatch(终端操作)可以确保流中没有任何元素与给定的谓词匹配。

boolean isHealthy = menu.stream()

.noneMatch(d -> d.getCalories() >= 1000);

System.out.println(isHealthy);

noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
findAny(终端操作)将返回当前流中的任意元素。

Optional<Dish> dish = menu.stream()

.filter(Dish::isVegetarian)

.findAny();

System.out.println(dish);

说是随机返回的,但是我测试了好几次都是返回的一样的,暂时未测试出来随机!(官网说是随机的,你们可自行测试)
findFirst(终端操作)有些流有一个出现顺序(encounter order)来指定流中项目出现的逻辑顺序(比如由List或排序好的数据列生成的流)。对于这种流,可能想要找到第一个元素。

List<Integer> someNumbers = Arrays.asList(1, 2, 3, 4, 5);

Optional<Integer> firstSquareDivisibleByThree = someNumbers.stream()

.map(x -> x * x)

.filter(x -> x % 3 == 0)

.findFirst();

System.out.println(firstSquareDivisibleByThree);

返回同一个值(返回同一个值)
forEach(终端操作)遍历流

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);

numbers.stream()

.filter(i -> i % 2 == 0)

.distinct()

.forEach(System.out::println);

遍历numbers
collect(终端操作)收集器

List<String> traderStr = menu.stream()

.map(transaction -> transaction.getName())

.sorted()

.collect(toList());

把map返回的数据收集起来,返回成List

 

reduce

(终端操作)归约reduce接受两个参数:

•一个初始值,这里是0;

•一个BinaryOperator<T>来将两个元素结合起来产生一个新值,这里我们用的是lambda (a, b) -> a + b。

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);

int sum = numbers.stream().reduce(0, (a, b) -> a + b);

System.out.println(sum);

简单来说reduce这个方法会返回计算的值(可在里面加减乘除,但是必须按顺序,可以扩充参数)
count(终端操作)返回此流中元素的计数。

long evenNumbers = IntStream.rangeClosed(1, 100)

.filter(n -> n % 2 == 0)

.count();

System.out.println(evenNumbers);

算返回(1-100)%2总共有几个值

可以使用filter、distinct、skip和limit对流做筛选和切片。

•可以使用map和flatMap提取或转换流中的元素。

•可以使用findFirst和findAny方法查找流中的元素。可以用allMatch、noneMatch和anyMatch方法让流匹配给定的谓词。

•这些方法都利用了短路:找到结果就立即停止计算;没有必要处理整个流。

•可以利用reduce方法将流中所有的元素迭代合并成一个结果,例如求和或查找最大元素。

•filter和map等操作是无状态的,它们并不存储任何状态。reduce等操作要存储状态才能计算出一个值。sorted和distinct等操作也要存储状态,因为它们需要把流中的所有元素缓存起来才能返回一个新的流。这种操作称为有状态操作。

•流有三种基本的原始类型特化:IntStream、DoubleStream和LongStream。它们的操作也有相应的特化。

•流不仅可以从集合创建,也可从值、数组、文件以及iterate与generate等特定方法创建。

•无限流是没有固定大小的流。

 

示例:

package com.example.demo.util;

import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @ClassName Dish
 * @Description TODO
 * @Author zhurongfei
 * @Data 2020/4/24 17:21
 * Version 1.0
 **/
public class Dish {
    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;

    public Dish(String name, boolean vegetarian, int calories, Type type) {
        this.name = name;
        this.vegetarian = vegetarian;
        this.calories = calories;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public boolean isVegetarian() {
        return vegetarian;
    }

    public int getCalories() {
        return calories;
    }

    public Type getType() {
        return type;
    }

    public enum Type { MEAT, FISH, OTHER }

    @Override
    public String toString() {
        return name;
    }

    public static final List<Dish> menu =
            Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
                    new Dish("beef", false, 700, Dish.Type.MEAT),
                    new Dish("chicken", false, 400, Dish.Type.MEAT),
                    new Dish("french fries", true, 530, Dish.Type.OTHER),
                    new Dish("rice", true, 350, Dish.Type.OTHER),
                    new Dish("season fruit", true, 120, Dish.Type.OTHER),
                    new Dish("pizza", true, 550, Dish.Type.OTHER),
                    new Dish("prawns", false, 400, Dish.Type.FISH),
                    new Dish("salmon", false, 450, Dish.Type.FISH));

    public static void main(String[] args) {
        List<Dish> vegetarianMenu = menu.stream()
                .filter(Dish::isVegetarian)
                .collect(toList());
        System.out.println(vegetarianMenu);
    }
}

打出来:

可以看到是true的都被打出来了!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值