Java 8 Working with streams(使用流)Filtering(筛选)示例

来源:互联网 发布:那个网络射击游戏好玩 编辑:程序博客网 时间:2024/04/29 16:48

问题描述:你将如何使用流过滤头两个肉类菜肴?
答案:
Dish.java:

import java.util.*;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("season fruit", true, 120, Dish.Type.OTHER),                           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("pizza", true, 550, Dish.Type.OTHER),                           new Dish("prawns", false, 400, Dish.Type.FISH),                           new Dish("salmon", false, 450, Dish.Type.FISH));}

Filtering.java:

import lambdasinaction.chap4.*;import java.util.stream.*;import java.util.*;import static java.util.stream.Collectors.toList;import static lambdasinaction.chap4.Dish.menu;public class Filtering{    public static void main(String...args){        //dishesSkip3.forEach(System.out::println);        List<Dish> dishesSkip3 =                menu.stream()                    .filter(d -> d.getType()==Dish.Type.MEAT)                    .limit(2)                    .collect(toList());            dishesSkip3.forEach(System.out::println);    }}