簡體   English   中英

轉換列表<Map<Long, String> &gt; 列出<Long>爪哇 8

[英]Convert List<Map<Long, String>> to List<Long> Java 8

我有一個地圖列表,其中每個地圖只有one key-value pair 我需要將其轉換為僅鍵列表。 我正在嘗試使用流如下:

List<Map<Long, String>> lst = // some data
List<Long> successList = lst.stream().map(ele -> ele.keySet().toArray()[0]).collect(Collectors.toList());

但我最終收到以下錯誤:

java: incompatible types: inference variable T has incompatible bounds
  equality constraints: java.lang.Long
  lower bounds: java.lang.Object

我該如何解決這個問題或者有什么更好的方法?

使用Stream#flatMap如下:

lst.stream()
   .flatMap(e->e.entrySet().stream())
   .map(e->e.getKey())
   .collect(Collectors.toList());

編輯:(根據評論)更優雅的方式是使用Map#keySet而不是Map#entrySet

lst.stream()
   .flatMap(e -> e.keySet().stream())
   .collect(Collectors.toList());

你只需要:

List<Long> successList = lst.stream()
        .flatMap(e -> e.keySet().stream())
        .collect(Collectors.toList());

雖然已經發布了更好的答案( flatMap是你的朋友),但我認為值得在這里指出的是,打字錯誤源於不帶參數的toArray的使用。

jshell> List<Long> a = Arrays.asList(1L, 2L, 3L, 4L)
a ==> [1, 2, 3, 4]

jshell> a.toArray()
$2 ==> Object[4] { 1, 2, 3, 4 }

看那里? 當您使用不帶參數的toArray ,您會得到Object[]類型的結果。 所以改為這樣做:

jshell> a.toArray(new Long[1])
$3 ==> Long[4] { 1, 2, 3, 4 }

通過添加參數new Long[1]我們強制toArray的結果是您想要的new Long[1]數組,而不是對象數組。

請參閱“toArray”JavaDoc

用這個:

lst.stream().flatMap(m -> m.entrySet().stream()).map(Map.Entry::getKey).collect(toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM