繁体   English   中英

为什么此Java流的一个版本可以在静态地图上工作,而另一个版本却失败?

[英]Why does one version of this Java stream work on a Static Map while the other fails?

我有一张静态地图:

private static final Map<SomeObject, AnotherObject> SOME_MAP = ...build map here...

我正在尝试生成类型为List<AnotherObject>的单个列表

这按预期工作:

List<AnotherObject> list = Stream.of(SOME_MAP.values())
  .flatMap(Collection::stream)
  .collect(Collectors.toList());

由于非静态方法无法在静态上下文中引用,因此以下操作失败

List<AnotherObject> list = SOME_MAP.values().stream()
  .flatMap(Collection::stream)
  .collect(Collectors.toList());

谁能确切解释第二个版本如何引起非静态方法错误而第一个版本没有?

这是一个具体的例子:

private static final Map<Integer, Integer> SOME_MAP = ImmutableMap.of(1, 2, 3, 4, 5, 6);

@Test
public void workingTest() {
 List<Integer> list = Stream.of(SOME_MAP.values())
    .flatMap(Collection::stream)
    .collect(Collectors.toList());

   System.out.println(list); // prints out [2, 4, 6]
}


@Test
public void nonWorkingTest() {
 List<Integer> list = SOME_MAP.values().stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toList());

   System.out.println(list); // Fails before this.
}

通过失败的测试,我得到以下错误:

Error:(79, 17) java: incompatible types: cannot infer type-variable(s) R
(argument mismatch; invalid method reference
  method stream in interface java.util.Collection<E> cannot be applied to given types
    required: no arguments
    found: java.lang.Integer
    reason: actual and formal argument lists differ in length)

 Error:(79, 18) java: invalid method reference
    non-static method stream() cannot be referenced from a static context

答案很简单。 两种变体都返回不同的流。

Stream.of(SOME_MAP.values())产生Stream<Collection<AnotherObject>>

另一方面, SOME_MAP.values().stream()产生Stream<AnotherObject> 您无需在其上调用Stream::flatMap

暂无
暂无

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

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