[英]convert hashmap items into another object and return as a list in java
[英]Java: Convert an Object List into a hashmap inside of another hashmap
我有一个要转换为 hash map 的对象列表。 是否可以创建这种类型的哈希映射Map<String, Map<String, List<Object>>
?
这样做的原因是我需要按对象中的某些属性对它们进行排序,以便以后可以遍历它。 下面是 Json 对象当前的样子:
[
object1: {plan: "11", relationship: "A", etc...},
object2: {plan: "12", relationship: "A", etc...},
object3: {plan: "11", relationship: "B", etc...},
]
I was trying to use Collectors
to get it into a HashMap
but i am confused on the second hash map, I can't seem to get the list of relationships into a Map
.
Map<String, Map<String, List<myObject>> myHash = objectList
.stream()
.collect(Collectors.toMap(myObject::plan,
a -> a.stream().collect(Collectors.groupingBy(myObject::relationship))));
我想得到的是这样的
[
{
key: "11",
value: [
{key: "A", value: [ object1 ]},
{key: "B", value: [ object3 ]}
]
},
{
key: "12",
value: [{key: "A", value: [ object2 ]}]
}
]
您可以分组两次,“关系”分组收集器是“计划”分组收集器的下游:
Map<String, Map<String, List<myObject>> myHash = objectList
.stream()
.collect(Collectors.groupingBy(myObject::getPlan,
Collectors.groupingBy(myObject::getRelationship)));
这将使每个“计划”组下的“关系”组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.