|
| 1 | +package com.brianway.learning.java8.lambda; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.function.Predicate; |
| 7 | + |
| 8 | +/** |
| 9 | + * Created by brian on 16/12/26. |
| 10 | + */ |
| 11 | +public class FilteringApples { |
| 12 | + public static void main(String[] args) { |
| 13 | + List<Apple> inventory = Arrays.asList(new Apple(80, "green"), |
| 14 | + new Apple(155, "green"), |
| 15 | + new Apple(120, "red")); |
| 16 | + |
| 17 | + List<Apple> greenApples = filter(inventory, FilteringApples::isGreenApple); |
| 18 | + System.out.println(greenApples); |
| 19 | + |
| 20 | + List<Apple> greenApples2 = filter(inventory, (Apple a) -> "green".equals(a.getColor())); |
| 21 | + System.out.println(greenApples2); |
| 22 | + |
| 23 | + List<Apple> heavyApples = filter(inventory, FilteringApples::isHeavyApple); |
| 24 | + System.out.println(heavyApples); |
| 25 | + |
| 26 | + List<Apple> heavyApples2 = filter(inventory, (Apple a) -> a.getWeight() > 150); |
| 27 | + System.out.println(heavyApples2); |
| 28 | + |
| 29 | + } |
| 30 | + |
| 31 | + public static List<Apple> filter(List<Apple> inventory, Predicate<Apple> p) { |
| 32 | + List<Apple> result = new ArrayList<>(); |
| 33 | + for (Apple apple : inventory) { |
| 34 | + if (p.test(apple)) { |
| 35 | + result.add(apple); |
| 36 | + } |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | + |
| 41 | + public static boolean isGreenApple(Apple apple) { |
| 42 | + return "green".equals(apple.getColor()); |
| 43 | + } |
| 44 | + |
| 45 | + public static boolean isHeavyApple(Apple apple) { |
| 46 | + return apple.getWeight() > 150; |
| 47 | + } |
| 48 | + |
| 49 | + public static class Apple { |
| 50 | + private int weight = 0; |
| 51 | + private String color = ""; |
| 52 | + |
| 53 | + public Apple(int weight, String color) { |
| 54 | + this.weight = weight; |
| 55 | + this.color = color; |
| 56 | + } |
| 57 | + |
| 58 | + public Integer getWeight() { |
| 59 | + return weight; |
| 60 | + } |
| 61 | + |
| 62 | + public void setWeight(Integer weight) { |
| 63 | + this.weight = weight; |
| 64 | + } |
| 65 | + |
| 66 | + public String getColor() { |
| 67 | + return color; |
| 68 | + } |
| 69 | + |
| 70 | + public void setColor(String color) { |
| 71 | + this.color = color; |
| 72 | + } |
| 73 | + |
| 74 | + public String toString() { |
| 75 | + return "Apple{" + |
| 76 | + "color='" + color + '\'' + |
| 77 | + ", weight=" + weight + |
| 78 | + '}'; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments