1、 Consumer interface :Consumer
(1) Functional interface
@FunctionalInterface public interface Consumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t);
Test class
public void happy(String string, Consumer<String> con) { con.accept(string); } @Test public void test1() { happy("zhai", (m) -> System.out.println(" Hello " + m )); }
Hello zhai
Features of consumer interface : There is input but no return value
2、 Supply type interface :Supplier
(1) Functional interface
@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
(2) test
public List<Integer> getNumList(int num, Supplier<Integer> sup) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < num; i++) { Integer n = sup.get(); list.add(n); } return list; } @Test public void test2() { List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100)); for (Integer num : numList) { System.out.println(num); } }
75 1 61 85 97 25 94 41 24 90
No input parameters , Have output
3、 Functional interface :Function
(1) Functional interface
@FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t);
(2) test
@FunctionalInterface public interface Function<T, R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t);
Hello
llo
There are input parameters , There is a return value
4、 Assertion interface :Predicate
(1) Functional interface
@FunctionalInterface public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t);
(2) test
public List<String> filterStr(List<String> list, Predicate<String> pre) { List<String> strList = new ArrayList<>(); for (String str : list) { if (pre.test(str)) { strList.add(str); } } return strList; } @Test public void test4() { List<String> list = Arrays.asList("Hello", "nihaoyyyy", "Lambda", "www", "ok"); List<String> strList = filterStr(list, (s) -> s.length() > 3); for (String str : strList) { System.out.println(str); } }
There's input , The return value is Boolean Type of
5、 Other interfaces
(1) Other interfaces