在流收集器中编写 Java 8 个方法引用

Composing Java 8 method references in stream collector

我想在流的 collect(Collectors.toMap(..)) 调用中编写方法引用。在以下示例中,我的代码无需方法引用即可完成我的任务:

class A {
    private String property1;
    private B property2;

    public String getProperty1() { return property1; }
    public B getProperty2() { return property2; }
}

class B {
    private String property3;

    public String getProperty3() { return property3; }
}

public class Main {
    public static void Main() {
        List<A> listOfA = /* get list */;

        Map<String, String> = listOfA.stream()
            .collect(toMap(x -> x.getProperty1(), x -> x.getProperty2().getProperty3()));
    } 
}

x -> x.getProperty1() 更改为 A::getProperty1() 是微不足道的。然而,x -> x.getProperty2().getProperty3() 并不那么简单。我想要以下其中一项工作:

.collect(toMap(A::getProperty1, ((Function)A::getProperty2).andThen((Function)B::getProperty3)))

.collect(toMap(A::getProperty1, ((Function)B::getProperty3).compose((Function)A::getProperty2)))

但是,他们都给我错误Non-static method cannot be referenced from static context

A::getProperty2 是一个 Function<A, B>(这是一个接受 A 实例和 returns B 实例的函数)。

您可以将其转换为:

((Function<A, B>)A::getProperty2).andThen(B::getProperty3)

或者您可以像这样创建函数生产者:

public static <A, B, R> Function<A, R> compose(
        Function<A, B> f1, Function<B, R> f2) {
    return f1.andThen(f2);
}

并用它来组成:

compose(A::getProperty2, B::getProperty3)