方法引用通过复用已有方法替代单方法调用的Lambda表达式,使代码更简洁、意图更明确,分为静态、绑定实例、未绑定实例和构造器四类,严格匹配函数式接口签名,不可添加额外逻辑。
方法引用通过复用已有方法替代冗长的 Lambda 表达式,直接让代码更短、意图更明确。它不新增逻辑,而是把“调用什么方法”这件事表达得更直白。
当 Lambda 体只做一件事:调用一个已有方法,且参数和返回值完全匹配,就可直接替换。
list.forEach(item -> System.out.println(item))
list.forEach(System.out::println)
list.sort((a, b) -> a.compareTo(b)) → list.sort(String::compareTo)
stream.map(s -> s.toUpperCase()) → stream.map(String::toUpperCase)
不是所有方法都能随便引用,必须看目标函数式接口的抽象方法签名(参数个数、类型顺序、返回值)是否与被引用方法一致。
Integer::parseInt(对应 Function<String, Integer>)str::length(str 是确定对象,对应 Supplier<Integer>)String::length(接收一个 String 参数并调用其 length(),对应 Function<String, Integer>)ArrayList::new(对应 Supplier<List> 或 Function<Integer, List> 等)在 Stream 链式调用中,方法引用让每一步操作语义清晰,避免层层包裹的箭头函数。
立即学习“Java免费学习笔记(深入)”;
list.stream().filter(Objects::nonNull).map(String::trim).collect(toList())
optional.orElseThrow(() -> new IllegalArgumentException("empty")) → 若有 throwIfEmpty() 方法,可写为 optional.orElseThrow(this::throwIfEmpty)
people.stream().sorted(Comparator.comparing(Person::getName)),比写完整 Lambda 更易读方法引用是“原样委托”,不支持中间加工。一旦需要额外处理,就得退回 Lambda 或封装新方法。
s -> "ID_" + s.toUpperCase() 无法用 String::toUpperCase 直接替代static String formatId(String s) { return "ID_" + s.toUpperCase(); },再引用 MyClass::formatId
String::length 赋给 Consumer<String> 就会报错(返回 int,但 Consumer 要求无返回)