JAVA8 - 流 - 查找和匹配

佚名 / 2024-01-20 / 原文

查找和匹配

Dish 类:

package com.demo3;

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;
    }

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

    public enum  Type {MEAT, FISH, OTHER}

}

anyMatch、allMatch、noneMatch 这三个操作都用到了我们所谓的短路,这就是大家熟悉的JAVA中 && 和 || 运算符短路在流中的版本

package com.demo3;

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

public class Test1 {

    public  static 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("reason fruit",true,120,Dish.Type.OTHER)
    );

    public static void main(String[] args) {
        test1();
    }
    
    public static void test1(){
        //检查谓词是否至少匹配一个元素
        if (menu.stream().anyMatch(Dish::isVegetarian)){
            System.out.println("The menu is (somewhat) vegetarian friendly!!");
        }

        //检查谓词是否匹配所有元素
        boolean b = menu.stream().anyMatch(d -> d.getCalories() < 1000);
        System.out.println(b);  //ture


        boolean b1 = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
        System.out.println(b1); //true
    }
}