如何在数组对象的情况下读取特定的地图键值

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

How to read Specific Map Key Value in case of an Array Object

问题

我有以下的Map结构

  1. {empId=1234, empName=Mike, CDetails=[{"collegeName":"Peters Stanford","collegeLoc":"UK","collegeLoc":"UK"}]}

我需要从上述Map中读取collegeLoc这个值

我尝试了以下的方式,它能够工作,但是否有更好的方法

  1. myMap.entrySet().stream().filter(map -> map.getKey().equals("CDetails")).forEach(e -> {
  2. List<Object> objsList = (List<Object>) e.getValue();
  3. for(int i=0; i<objsList.size(); i++)
  4. {
  5. HashMap<String,String> ltr = (HashMap<String, String>) objsList.get(i);
  6. System.out.println(ltr.get("collegeLoc"));
  7. }
  8. });
英文:

I have the following Map structure

  1. {empId=1234, empName=Mike, CDetails=[{&quot;collegeName&quot;:&quot;Peters Stanford&quot;,&quot;collegeLoc&quot;:&quot;UK&quot;,&quot;collegeLoc&quot;:&quot;UK&quot;}]}

I need to read the value collegeLoc from the above Map

I tried this way , its working , but is there any better way

  1. myMap.entrySet().stream().filter(map -&gt; map.getKey().equals(&quot;CDetails&quot;)).forEach(e -&gt; {
  2. List&lt;Object&gt; objsList = (List&lt;Object&gt;) e.getValue();
  3. for(int i=0;i&lt;objsList.size();i++)
  4. {
  5. HashMap&lt;String,String&gt; ltr = (HashMap&lt;String, String&gt;) objsList.get(i);
  6. System.out.println(ltr.get(&quot;collegeLoc&quot;));
  7. }
  8. });

答案1

得分: 1

CDetails是一个*List*,而不是Map

尝试这样做:

  1. empMap.entrySet().stream()
  2. .map(map -> map.get("CDetails"))
  3. .filter(Objects::nonNull)
  4. .flatMap(List::stream)
  5. .map(element -> ((Map)element).get("collegeLoc"))
  6. .filter(Objects::nonNull)
  7. .forEach(System.out::println);
英文:

CDetails is a List, not a Map.

Try this:

  1. empMap.entrySet().stream()
  2. .map(map -&gt; map.get(&quot;CDetails&quot;))
  3. .filter(Objects::nonNull)
  4. .flatMap(List::stream)
  5. .map(element -&gt; ((Map)element).get(&quot;collegeLoc&quot;))
  6. .filter(Objects::nonNull)
  7. .forEach(System.out::println);

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

发表评论

匿名网友

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

确定