簡體   English   中英

如何從集合中提取地圖值

[英]How to extract Map values from set

我的地圖下面有鍵=值對,現在如何從集合{}中獲取GCO值?

MAP : {containerIdentifier={ID=null, dto=null, GCO=123, version=1}, containerEditable=true}

代碼:

        for (Entry<String, Object> entry : map.entrySet())
System.out.println("Key = " + entry.getKey() +", Value = " + entry.getValue());

輸出:

Key = containerIdentifier, Value = {ID =null, dto=null, GCO=123, version=1}
Key = containerEditable, Value = true

如何從價值中獲得唯一的GCO 123?

您必須檢查原始Map的值是否也是Map 然后,您可以將其轉換為Map並在該內部Map查找特定鍵的值:

for (Entry<String, Object> entry : map.entrySet()) {
    if (entry.getValue() instanceof Map) {
        Map innermap = (Map) entry.getValue();
        System.out.println(innermap.get("GCO"));
    }
}

這是假設原始Map值並不總是Map (並且考慮示例Map的第二個條目,其值為Boolean ,該假設是正確的)。

您可以使用Java Steam API。

map.values().stream()
            .flatMap(innerMaps -> innerMaps.entrySet().stream())
            .filter(entry-> "GCO".equals(entry.getKey()))
            .map(Map.Entry::getValue)
            .findAny().orElse("not found")

暫無
暫無

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

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