簡體   English   中英

使用現有列表中HashMap中的值創建一個新列表

[英]Create a new list with values from HashMap from existing list

我想從現有列表中的Map創建一個新列表。

我得到一個如下的ArrayList結構;

ArrayList
         0 = {LinkedHashMap}
                   0 = {LinkedHashMapEntry} "name" --> "value"
                   1 = {LinkedHashMapEntry} "surname" --> "value"
         1 = {LinkedHashMap}
                   0 = {LinkedHashMapEntry} "name" --> "value"
                   1 = {LinkedHashMapEntry} "surname" --> "value"
         ....

我要做的是將所有名稱值作為新列表。

List<String> allNames = ....

有什么方法可以使用Java Stream獲得此列表?

是:

List<String> allNames =
    list.stream() // this creates a Stream<LinkedHashMap<String,String>>
        .map(m->m.get("name")) // this maps the original Stream to a Stream<String>
                               // where each Map of the original Stream in mapped to the
                               // value of the "name" key in that Map
        .filter(Objects::nonNull) // this filters out any null values
        .collect(Collectors.toList()); // this collects the elements
                                       // of the Stream to a List

暫無
暫無

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

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