I need to generate an output json like below
{
"account":{
"Alpha":{
"OLD":{
"long":"zerozerooneO",
"short":"001O"
},
"NEW":{
"long":"zerozerooneN",
"short":"001N"
}
},
"Beta":{
"OLD":{
"long":"zerozerooneO",
"short":"001O"
},
"NEW":{
"long":"zerozerooneN",
"short":"001N"
}
}
}
}
From a List of object with sample below
[
{
"codetype":"Alpha",
"shortOldCode":"001O",
"longOldCode":"zerozerooneO",
"shortNewCode":"001N",
"longNewCode":"zerozerooneN"
},
{
"codetype":"Beta",
"shortOldCode":"001O",
"longOldCode":"zerozerooneO",
"shortNewCode":"001N",
"longNewCode":"zerozerooneN"
}
]
I have tried something like this
Map<String, Map<String, Map<String, List<Object>>>> newList = new HashMap<>();
newList = dataMap.stream()
.filter(distinctByKey(code -> code.getCodeType())).collect(
groupingBy((GetCodeTypes a) -> "account",
groupingBy((GetCodeTypes b) -> b.getCodeType(),
groupingBy((GetCodeTypes c) -> "OLD",
mapping(
v -> {
GetCodeTypesResponse.Old
oldCode = new GetCodeTypesResponse.Old();
oldCode.setLongs(v.getLongOldCode());
oldCode.setShorts(v.getShortOldCode());
return oldCode;
}, toList())))));
Hoping anyone could point me in a right direction to get the desired output using hashmap in Java 8.I know grouping/mapping with record might work with new version of Java but the project I am working on is Java 1.8 and I would like to use Java Streams to solve this if possible.
2
Answers
Here is a reasonable, but non-stream based solution to your problem:
This is a simple non-stream solution that use JSON library to do the transformation.
https://github.com/octomix/josson
Output