-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestMain03.java
More file actions
72 lines (58 loc) · 1.57 KB
/
TestMain03.java
File metadata and controls
72 lines (58 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package lambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
* <p>Description: 将List类型抽象化</p>
*
* @author dbx
* @since 2021/4/23 16:44
*/
public class TestMain03 {
public static class Apple {
private String color;
private Integer weight;
public Apple(Integer weight,String color){
this.color = color;
this.weight = weight;
}
String getColor() {
return color;
}
Integer getWeight() {
return weight;
}
}
/**
* 谓词-行为,只有一个抽象方法的接口
*/
public interface Predicate<T>{
boolean test (T t);
default boolean test2 (T t){
return false;
}
}
/**
* 引入类型参数T
* @param list
* @param p
* @param <T>
* @return
*/
public static <T> List<T> filter(List<T> list, Predicate<T> p){
List<T> result = new ArrayList<>();
for(T e: list){
if(p.test(e)){
result.add(e);
}
}
return result;
}
public static void main(String[] args) {
List<Apple> inventory = Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red"));
List<Apple> redApples = filter(inventory, (Apple apple) -> "red".equals(apple.getColor()));
List<Integer> numbers = Arrays.asList(12,15,20);
List<Integer> evenNumbers = filter(numbers, (Integer i) -> i % 2 == 0);
}
}