java8传递代码例子

案例:

List中存放Apple实体类,找出color属性为green,重量大于150的apple(Java8实战第一章笔记)


Apple:

package unitOne;

/**
 * author : chengshanyunduo
 * create : 2017-08-14 0:00
 * desc   :
 **/
public class Apple {
    private String color;

    private Integer weight;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    //筛选color为green的方法
    public static boolean isGreenApple(Apple apple){
        return "green".equals(apple.getColor());
    }

    //筛选weight大于150的方法
    public static boolean isHeavyApple(Apple apple){
        return apple.getWeight() > 150;
    }

    public interface Predicate<T>{
        boolean test(T t);
    }
}




运行代码:

package unitOne;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * author : chengshanyunduo
 * create : 2017-08-14 0:00
 * desc   :
 **/
public class testUnitOne {
    public static void main(String[] args){
        List<Apple> apples = new LinkedList<Apple>();
        for (int i=0; i<9; i++){
            apples.add(new Apple());
        }
        apples.get(0).setColor("green");
        apples.get(1).setColor("red");
        apples.get(2).setColor("yellow");
        apples.get(3).setColor("green");
        apples.get(4).setColor("green");
        apples.get(5).setColor("red");
        apples.get(6).setColor("green");
        apples.get(7).setColor("red");
        apples.get(8).setColor("green");
        apples.get(0).setWeight(120);
        apples.get(1).setWeight(150);
        apples.get(2).setWeight(160);
        apples.get(3).setWeight(110);
        apples.get(4).setWeight(170);
        apples.get(5).setWeight(100);
        apples.get(6).setWeight(110);
        apples.get(7).setWeight(190);
        apples.get(8).setWeight(200);

        //将Apple中的方法作为变量传进方法中
        List<Apple> resultColor = filterApples(apples, Apple::isGreenApple);
        List<Apple> resultWeight = filterApples(apples, Apple::isHeavyApple);

        //检验结果
        for (int i=0; i<resultColor.size(); i++){
            System.out.println(i + ":" + resultColor.get(i).getColor());
        }
        for (int i=0; i<resultWeight.size(); i++){
            System.out.println(i + ":" + resultWeight.get(i).getWeight());
        }
    }


    /**
     * 筛选方法
     * @param inventory
     * @param p
     * @return
     */
    static List<Apple> filterApples(List<Apple> inventory, Apple.Predicate<Apple> p){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory){
            if (p.test(apple)){
                result.add(apple);
            }
        }
        return result;
    }
}

运行结果:


优点:

避免代码重复,方便代码修。

发布了55 篇原创文章 · 获赞 13 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览