Consumer<T> : 消費型接口
void accept(T t);
Supplier<T> : 提供型接口
T get();
Function<T, R> : 函數型接口
R apply(T t);
Predicate<T> : 斷言型接口
boolean test(T t);
public class MyFunction {
@Test
public void test1() {
happy(10000, m -> System.out.println("消費 " + m + " 元"));
}
public void happy(double money, Consumer<Double> con) {
con.accept(money);
}
@Test
public void test2() {
System.out.println(createIntegerList(10, () -> (int)(Math.random() * 100)));
}
public List<Integer> createIntegerList(int num, Supplier<Integer> supplier) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(supplier.get());
}
return list;
}
@Test
public void test3 () {
String str = "abcdefght";
System.out.println(strHandler(str, e -> str.substring(2, 4)));
}
public String strHandler(String str, Function<String, String> function) {
return function.apply(str);
}
@Test
public void test4() {
List<String> strings = Arrays.asList("aaaa", "bbbb", "cccccc", "dddd");
System.out.println(filterStr(strings, e -> e.length() <= 4));
}
public List<String> filterStr(List<String> list, Predicate<String> predicate) {
List<String> result = new ArrayList<>();
for (String str : list) {
if (predicate.test(str)) {
result.add(str);
}
}
return result;
}
}