简体   繁体   中英

Java 8 Stream API to get specific value

Having the below JSON structured value. I would like to get the value from the "KEY" in List of Strings

"Test": {
    "ONE": {
      "First_Layer": {
        "KEY": "VALUE_1"
      },
      "First_Layer_1": {
        "KEY": "VALUE_2"
      }
    },
    "TWO": {
      "First_Layer_2": {
        "KEY": "VALUE_3"
      }
    }
  }

Expected Output (List of String):

[VALUE_1, VALUE_2, VALUE_3]

Tried this and it is working with one layer, not with second layer

final Map<String, Map<String, String>> value = document.get("Test", Collections.emptyMap());
        return value.values().stream()
            .map(valueMap -> valueMap.get("KEY"))
            .collect(Collectors.toList());

Your data should deserialize into Map<String, Map<String, Map<String, String>>>

Then you can use flatMap to flat the first layer

List<String> res = data
        .entrySet()
        .stream()
        .flatMap(m -> m.getValue().entrySet().stream())
        .map(v-> v.getValue().get("KEY"))
        .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM