函数式接口
参考:https://juejin.im/post/5a69373ef265da3e5661b62b#heading-2
@Data public class Book { String author; Double money; public Book(String author, double money) { this.author = author; this.money = money; } }
public static <T, R> List<R> map(List<T> list, Function<T, R> f) { List<R> result = new ArrayList<>(); for(T s: list){ result.add(f.apply(s)); } return result; } public static void main(String[] args) { List<Book> books = Arrays.asList( new Book("张三", 99.00D), new Book("李老四", 59.00D), new Book("王二麻子", 59.00D) ); List<Integer> results = map(books, book -> book.getAuthor().length()); System.out.println(results.toString()); }
static void modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function){ int newValue = function.apply(valueToBeOperated); System.out.println(newValue); } public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); }
f.apply(s),s是参数,对参数执行f操作,返回操作后的结果。