Stream介绍

一、Stream介绍  

现在有这样的需求:有个菜单list,菜单里面非常多的食物列表,只选取小于400卡路里的并且按照卡路里排序,然后只想知道对应的食物名字。

代码:

package com.cy.java8;

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 "Dish{" +
                "name='" + name + '\'' +
                ", vegetarian=" + vegetarian +
                ", calories=" + calories +
                ", type=" + type +
                '}';
    }
}
View Code
package com.cy.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SimpleStream {

    public static void main(String[] args) {
        //have a dish list (menu)
        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, 300, Dish.Type.FISH),
                new Dish("salmon", false, 450, Dish.Type.FISH));

        List<String> lowerCaloriesDish = getLowerCaloriesDish(menu);
        System.out.println(lowerCaloriesDish);

        List<String> lowerCaloriesDish2 = getLowerCaloriesDish2(menu);
        System.out.println(lowerCaloriesDish2);
    }

    /**
     * 用Stream的方式去写
     */
    private static List<String> getLowerCaloriesDish2(List<Dish> menu){
        return menu.stream().filter(dish -> dish.getCalories() < 400)
                            .sorted(Comparator.comparing(d->d.getCalories()))
                            .map(Dish::getName)
                            .collect(Collectors.toList());
    }

    /**
     * 以前的写法
     * 获取卡路里小于400的食物列表,并且排好序,只返回食物的名字;
     * @param menu
     * @return
     */
    private static List<String> getLowerCaloriesDish(List<Dish> menu){
        List<Dish> lowerCalories = new ArrayList<>();
        //filter and get calories less 400
        for(Dish  dish : menu){
            if(dish.getCalories() < 400 ){
                lowerCalories.add(dish);
            }
        }
        //sort
        lowerCalories.sort((o1, o2) -> o1.getCalories() - o2.getCalories());

        List<String> lowerCaloreisDishList = new ArrayList<>();
        for(Dish dish : lowerCalories){
            lowerCaloreisDishList.add(dish.getName());
        }
        return lowerCaloreisDishList;
    }
}

console打印:

[season fruit, prawns, rice]
[season fruit, prawns, rice]

Stream:升级版的api,处理集合等等,有个好处是可以并行处理,而且不需要关心并行处理的细节,

 

二、Stream的简单用法介绍

围绕着stream的一些方法进行一些代码的举例:

package com.cy.java8;

import java.util.*;
import java.util.stream.Stream;

public class SimpleStream {

    public static void main(String[] args) {
        //have a dish list (menu)
        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, 300, Dish.Type.FISH),
                new Dish("salmon", false, 450, Dish.Type.FISH));

        System.out.println("method1 the max calories dish is: " + getMaxCaloriesDish(menu));
        System.out.println("method2 the max calories dish is: " + getMaxCaloriesDish2(menu));
        System.out.println("have dish calories larger than 600: " + foundDishCaloriesLarger600(menu));
        System.out.println("all dish calories larger than 400: " + allDishCaloriesLarger400(menu));
        System.out.println("---------------------------------------");

        /**
         * 创建一个stream
         */
        Stream<Dish> stream = Stream.of(new Dish("prawns", false, 300, Dish.Type.FISH),
                new Dish("salmon", false, 450, Dish.Type.FISH));
        stream.forEach(System.out::println);
    }

    /**
     * 找出热量最大的食物名字
     */
    private static String getMaxCaloriesDish(List<Dish> menu){
       return menu.stream().max(Comparator.comparingInt(Dish::getCalories)).get().getName();
    }

    /**
     * 找出热量最大的食物,方法二
     */
    private static String getMaxCaloriesDish2(List<Dish> menu){
        Optional<Dish> maxDish = menu.stream().sorted((d1, d2) -> d2.getCalories() - d1.getCalories()).findFirst();
        return maxDish.get().getName();
    }

    /**
     *  菜单里面是否有食物热量大于600
     */
    private static boolean foundDishCaloriesLarger600(List<Dish> menu){
        boolean result = menu.stream().anyMatch(dish -> dish.getCalories() > 600);
        return result;
    }

    /**
     * 菜单里面食物的热量是否都大于400
     */
    private static boolean allDishCaloriesLarger400(List<Dish> menu){
        boolean result = menu.stream().allMatch(dish -> dish.getCalories() > 400);
        return result;
    }
}

打印结果:

method1 the max calories dish is: pork
method2 the max calories dish is: pork
have dish calories larger than 600: true
all dish calories larger than 400: false
---------------------------------------
Dish{name='prawns', vegetarian=false, calories=300, type=FISH}
Dish{name='salmon', vegetarian=false, calories=450, type=FISH}

 

 

 

 

--

 

转载于:https://www.cnblogs.com/tenWood/p/11487763.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值