为什么这个Java流的一个版本在静态地图上工作而另一个版本失败?

Ray*_*Ray 1 java java-8 java-stream

我有一张静态地图:

private static final Map<SomeObject, AnotherObject> SOME_MAP = ...build map here...
Run Code Online (Sandbox Code Playgroud)

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

这按预期工作:

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

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

List<AnotherObject> list = SOME_MAP.values().stream()
  .flatMap(Collection::stream)
  .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

任何人都可以确切地解释第二个版本如何在第一个版本没有的情况下包含非静态方法错误?

这是一个具体的例子:

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.
}
Run Code Online (Sandbox Code Playgroud)

在失败的测试中,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

fir*_*uel 8

答案很简单.两种变体都回馈不同的Streams.

Stream.of(SOME_MAP.values())导致Stream<Collection<AnotherObject>>.

另一方面SOME_MAP.values().stream()导致a Stream<AnotherObject>.你不需要打电话Stream::flatMap.

  • 你的意思是"Stream <Collection <AnotherObject >>",对吧? (4认同)
  • 没错.假设他们有相同的结果,但看到他们没有返回相同的流. (2认同)