Java 8 Stream API 获取特定值

huangapple go评论78阅读模式
英文:

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"

"Expected Output (List of String):"

"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());"

英文:

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

&quot;Test&quot;: {
    &quot;ONE&quot;: {
      &quot;First_Layer&quot;: {
        &quot;KEY&quot;: &quot;VALUE_1&quot;
      },
      &quot;First_Layer_1&quot;: {
        &quot;KEY&quot;: &quot;VALUE_2&quot;
      }
    },
    &quot;TWO&quot;: {
      &quot;First_Layer_2&quot;: {
        &quot;KEY&quot;: &quot;VALUE_3&quot;
      }
    }
  }

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&lt;String, Map&lt;String, String&gt;&gt; value = document.get(&quot;Test&quot;, Collections.emptyMap());
        return value.values().stream()
            .map(valueMap -&gt; valueMap.get(&quot;KEY&quot;))
            .collect(Collectors.toList());

答案1

得分: 2

你的数据应该反序列化为 Map<String, Map<String, Map<String, String>>>

然后你可以使用 flatMap 来扁平化第一层

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

Your data should deserialize into Map&lt;String, Map&lt;String, Map&lt;String, String&gt;&gt;&gt;

Then you can use flatMap to flat the first layer

List&lt;String&gt; res = data
        .entrySet()
        .stream()
        .flatMap(m -&gt; m.getValue().entrySet().stream())
        .map(v-&gt; v.getValue().get(&quot;KEY&quot;))
        .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年8月5日 02:01:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63252657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定