繁体   English   中英

在流收集器中编写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实例并返回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)

使用 Java 8

[英]Getting the stream object in Collectors toMap method using Method References in Java 8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM