簡體   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