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

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

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

问题

我有以下的Map结构

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

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

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

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

I have the following Map structure

{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

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

答案1

得分: 1

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

尝试这样做:

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

CDetails is a List, not a Map.

Try this:

empMap.entrySet().stream()
  .map(map -&gt; map.get(&quot;CDetails&quot;))
  .filter(Objects::nonNull)
  .flatMap(List::stream)
  .map(element -&gt; ((Map)element).get(&quot;collegeLoc&quot;))
  .filter(Objects::nonNull)
  .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:

确定