双冒号运算符可以引用源对象本身吗?

Can the Double Colon Operator reference the Source Object itself?

在某些情况下,当我在对象列表上使用 Stream 时,我喜欢通过 Collectors.toMap 函数收集它们,并将一个重要的属性指定为键,将对象本身指定为值,例如这种情况:

Map<String, SampleObject> map = list.stream()
    .collect(Collectors.toMap(SampleObject::getImportantValue, v -> v));

通常我使用双冒号运算符来分配键,但对于值我求助于 v -> v 结构。

这让我想知道:

有没有办法通过使用双冒号将对象本身赋值为匿名函数的 return 值?根据我自己的测试,SampleObjectSampleObject:: 似乎不起作用。 (仅合乎逻辑,因为前者仅引用 class 而后者期望遵循一个方法)

作为一种天真的方法,我希望在功能上与此类似:

...collect(Collectors.toMap(SampleObject::getImportantValue, SampleObject::));

您可以使用 Function.identity() 而不是使用 v->v,效果相同。我个人更喜欢第二种方法,但不会说一种真的比另一种好。如果您有兴趣,可以阅读 this answer 中的差异。

您应该使用 JANO 提供的答案 – t -> tFunction.identity()

但是,如果您真的真的想要使用方法参考,您可以推出自己的方法:

class Functions {
    static <T> T identity(T t) {
        return t;
    }
}

然后突然

.collect(Collectors.toMap(SampleObject::getImportantValue, Functions::identity));

有效。