您无法完全执行所需的操作-方法引用中不允许使用显式参数。
但是你可以…
…创建一个方法,该方法返回一个布尔值并将其调用编码为
getAttribute("style"):public boolean getAttribute(final T t) { return t.getAttribute("style");}这将允许您使用方法ref:
int a = (int) blogImagesList.stream() .map(this::getAttribute) .filter(s -> s.contains(imageSrc)) .count();
…或者您可以定义一个变量来保存该函数:
final Function<T, R> mapper = t -> t.getAttribute("style");这将允许您简单地传递变量
int a = (int) blogImagesList.stream() .map(mapper) .filter(s -> s.contains(imageSrc)) .count();
…或者您可以咖喱和结合上述两种方法(这绝对是过分的杀伤力)
public Function<T,R> toAttributeExtractor(String attrName) { return t -> t.getAttribute(attrName);}然后,您需要调用
toAttributeExtractor获取一个
Function并将其传递给
map:
final Function<T, R> mapper = toAttributeExtractor("style");int a = (int) blogImagesList.stream() .map(mapper) .filter(s -> s.contains(imageSrc)) .count();尽管实际上,仅使用lambda会更容易(就像您在下一行中所做的那样):
int a = (int) blogImagesList.stream() .map(t -> t.getAttribute("style")) .filter(s -> s.contains(imageSrc)) .count();


