java 8 四大内置函数接口使用示例

Consumer 接口

1
2
3
public interface Consumer<T> {
void accept(T t);
}
1
2
3
public void happy(double money, Consumer<Double> consumer) {
consumer.accept(money);
}
1
happy(1000, money -> System.out.println("吃喝玩乐"));
1
happy(10000, money -> System.out.println("旅游"));

Supplier 接口

1
2
3
public interface Supplier<T> {
T get();
}
1
2
3
4
5
6
7
8
9
10
public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
List<Integer> list = new ArrayList<>();

for(int i = 0; i < num; i++) {
Integer n = supplier.get();
list.add(n);
}

return list;
}
1
getNumList(10, () -> (int)(Math.random() * 100))

Function 接口

1
2
3
public interface Function<T, R> {
R apply(T t);
}
1
2
3
public String strHandler(String str, Function<String, String> function) {
return function.apply(str);
}
1
strHandler("   Lambda  ", str -> str.trim().toUpperCase())

Predicate 接口

1
2
3
public interface Predicate<T> {
boolean test(T t);
}
1
2
3
4
5
6
7
8
9
10
11
public List<String> filterStr(List<String> list, Predicate<String> predicate) {
List<String> strList = new ArrayList<>();

for(String str : list) {
if(predicate.test(str)) {
strList.add(str);
}
}

return strList;
}
1
2
List<String> strings = Arrays.asList("Hello", "Lambda", "Function", "Java");
filterStr(strings, str -> str.length() > 5);