如何在Java8流中迭代Hashmap的Hashmap?
以下是一个例子:如何在Java8流中迭代Hashmap的Hashmap?,java,java-8,Java,Java 8,以下是一个例子: { "options": [ { "price": { "amount": 0 }, "serviceOption": { "activationDate": "string", "conflictsWith": [ "string" ], "content": { "name": "string", "shortText": "string" }, "dependsOn":
{
"options": [
{
"price": {
"amount": 0
},
"serviceOption": {
"activationDate": "string",
"conflictsWith": [
"string"
],
"content": {
"name": "string",
"shortText": "string"
},
"dependsOn": "string",
"durationPeriod": "MONTH",
"earliestDeactivationDate": "string",
"fee": 0,
"feePeriod": "MONTH",
"groupId": "string",
"installed": true,
"minimumDuration": 0,
"modifiable": true,
"productId": "string",
"scheduledDeactivationDate": "string",
"status": "RECURRING"
}
}
]
}
这里我需要得到groupId的值
根据我的需求,我已经将上面的json对象转换成Hashmap进行迭代,如何使用stream对Hashmap的Hashmap进行迭代
为了迭代HashMap,我使用了HashMap.entrySet.stream,但是接下来我应该做什么来进一步迭代呢
问题更新:这是您如何迭代可用选项的GroupID的方法:
options.stream().map(option -> option.get("serviceOption").get("groupId")).forEach(groupId -> /* Do something with each groupId here */)
从地图开始的一种方法是:
Map<String,Object> map = new HashMap<>(); // Your map initialization code goes here.
Stream<Entry<String, Object>> stream = map.entrySet().stream();
// put code to consume stream here.
为什么要使用流?既然您已经知道要获取的数据的路径,为什么不使用yourMap.getoptions来获取呢?我假设列表中只包含一个对象映射,请通过.get0选择它,然后在该映射上选择getserviceOption,该映射还包含可以调用getgroupId的对象映射。短字符串groupId=yourMap.getoptions.get0.getserviceOption.getgroupId;。我能理解你的方法。但是我应该只使用流。但是我应该只使用流为什么?有人在威胁你们吗?有可能通过流来实现吗?为什么流只能通过一条可能的路径,因为根据你们向我们展示的选项数组只包含一个对象?这毫无意义,让你的问题变得不清楚。我在hashmap中有上面的JSONObject。无论如何,上述方法都不起作用
Map<String,Object> map = new HashMap<>(); // Your map initialization code goes here.
Stream<Entry<String, Object>> stream = map.entrySet().stream();
// put code to consume stream here.