您的位置:首页 > 编程语言 > Java开发

java8传递代码例子

2017-08-13 22:57 211 查看
案例:

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

运行结果:



优点:

避免代码重复,方便代码修。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: