1 import java.util.ArrayList;
2 import java.util.Arrays;
3 import java.util.List;
4 import java.util.function.Predicate;
5 import java.util.stream.Collectors;
6
7 /**
8 * 在这里编写类的功能描述
9 *
10 * @author shangjinyu
11 * @created 2017/9/29
12 */
13 public class Notes {
14
15 //构造一个待筛选的list
16 List<Apple> inventory = Arrays.asList(new Apple(80, "green"),
17 new Apple(155, "green"),
18 new Apple(120, "red"));
19
20 //找出list中的所有的绿色苹果
21 //写法一
22 public List<Apple> filterGreenApples(List<Apple> inventory) {
23 List<Apple> result = new ArrayList<>();
24 for (Apple apple : inventory) {
25 if (apple.getColor().equals("green")) {
26 result.add(apple);
27 }
28 }
29 return result;
30 }
31
32 List<Apple> greenApples1 = filterGreenApples(inventory);
33
34 /*
35 public interface Predicate<T>{
36 boolean test(T t);
37 }
38 一个java8中的函数FunctionInterface接口
39 */
40
41 //写法二
42
43 public List<Apple> filterGreenApples(List<Apple> inventory, Predicate<Apple> p) {
44 List<Apple> result = new ArrayList<>();
45 for (Apple apple : inventory) {
46 if (p.test(apple)) {
47 result.add(apple);
48 }
49 }
50 return result;
51 }
52
53 //用法
54 List<Apple> greenApples2 = filterGreenApples(inventory, new Predicate<Apple>() {
55 @Override
56 public boolean test(Apple apple) {
57 return apple.getColor().equals("green");
58 }
59 });
60
61
62 public boolean isGreenApple(Apple apple) {
63 return apple.getColor().equals("green");
64 }
65
66 //lambdasin写法
67 List<Apple> greenApples3 = filterGreenApples(inventory, this::isGreenApple);
68 List<Apple> greenApples4 = filterGreenApples(inventory, (Apple apple) -> apple.getColor().equals("green"));
69 List<Apple> greenApples5 = filterGreenApples(inventory, item -> item.getColor().equals("green"));
70 //流
71 //顺序处理
72 List<Apple> greenApples6 = inventory.stream().filter(apple -> apple.getColor().equals("green")).collect(Collectors.toList());
73 //并行处理
74 List<Apple> greenApples7 = inventory.parallelStream().filter(apple -> apple.getColor().equals("green")).collect(Collectors.toList());
75
76 //一个实体类
77 public class Apple {
78 private int weight = 0;
79 private String color = "";
80
81 public Apple(int weight, String color) {
82 this.weight = weight;
83 this.color = color;
84 }
85
86 public Integer getWeight() {
87 return weight;
88 }
89
90 public void setWeight(Integer weight) {
91 this.weight = weight;
92 }
93
94 public String getColor() {
95 return color;
96 }
97
98 public void setColor(String color) {
99 this.color = color;
100 }
101
102 public String toString() {
103 return "Apple{" +
104 "color='" + color + '\'' +
105 ", weight=" + weight +
106 '}';
107 }
108 }
109 }