I have the following collection:
Map<String, Map<SomeEnum, Long>> map = ...
Here's sample data:
{"Foo": {
SomeEnum.BAR1: 1,
SomeEnum.BAR2: 2,
SomeEnum.BAR3: 3
},
"two": {...}
Since I know all enums, I want to convert it to the list of POJO. The definition of the object is as below:
class SomeClass {
String name;
long bar1Value;
long bar2Value;
long bar3Value;
}
I have tried different solutions, like with mapping inside mapping:
map.entrySet().stream()
.map(e -> e.getValue().entrySet().stream().map(innerEntry -> {
long bar1 = 0;
long bar2 = 0;
long bar3 = 0;
if(innerEntry.getKey().equals(SomeEnum.BAR1)) bar1 = innerEntry.getValue();
if(innerEntry.getKey().equals(SomeEnum.BAR2)) bar2 = innerEntry.getValue();
if(innerEntry.getKey().equals(SomeEnum.BAR3)) bar3 = innerEntry.getValue();
return new SomeClass(e.getKey(), bar1, bar2, bar3);
}).collect(toList()).collect(toList());
Unfortuantely, what I am getting is List<List<SomeClass>>
.
Is there any other, more elegant, way to handle this?
Would this work for you?
It requires a constructor for the target class but simply gets the values and creates an instance. Then it collects them to a list.
List<SomeClass> list = map.entrySet().stream()
.map(e -> new SomeClass(e.getKey(),
e.getValue().get(SomeEnum.BAR1),
e.getValue().get(SomeEnum.BAR2),
e.getValue().get(SomeEnum.BAR3)))
.collect(Collectors.toList());
Class with constructor
class SomeClass {
String name;
long bar1Value;
long bar2Value;
long bar3Value;
public SomeClass(String name, long bar1Value, long bar2Value,
long bar3Value) {
this.name = name;
this.bar1Value = bar1Value;
this.bar2Value = bar2Value;
this.bar3Value = bar3Value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With