Using the Java 8 Stream package I want to transform a List of arrays of type object into a List of a specific class object. The arrays on the first list contain field of the class loaded from the database.
This is the List of arrays of type object loaded from the DB:
List<Object[]> results = loadFromDB();
Every element Object[]
present in the list contains fields that I want to map to the following class:
class DeviationRisk {
Timestamp plannedStart;
Timestamp plannedEnd;
String rcsName;
BigDecimal riskValue;
BigDecimal mediumThreshold;
BigDecimal highThreshold;
Interval interval;
String getRcsName() {
return rcsName;
}
DeviationRisk(Object[] res) {
this((Timestamp) res[0], (Timestamp) res[1], (String) res[2], (BigDecimal) res[3], (BigDecimal) res[4], (BigDecimal) res[5]);
}
DeviationRisk(Timestamp start, Timestamp end, String rcs, BigDecimal risk, BigDecimal medium, BigDecimal high) {
plannedStart = start;
plannedEnd = end;
rcsName = rcs;
riskValue = risk;
mediumThreshold = medium;
highThreshold = high;
interval = new Interval(plannedStart.getTime(), plannedEnd.getTime());
}
DeviationRisk create(Object[] res) {
return new DeviationRisk(res);
}
List<DateTime> getRange() {
return DateUtil.datesBetween(new DateTime(plannedStart), new DateTime(plannedEnd));
}
}
As you can see every element Object[]
present in the original list results
it's just the array representation of the object DeviationRisk
Now, I know how to do this using loops it's just 3 lines of code as you can see below:
List<DeviationRisk> deviations = new ArrayList<>();
for (Object[] res : results) {
deviations.add(new DeviationRisk(res));
}
How to achieve the same result using Java 8 Streams?
array ] objects can be converted to a list with the tolist() function.
This will do it:
final List<DeviationRisk> l = results.stream()
.map(DeviationRisk::new).collect(Collectors.toList());
This work because DeviationRisk::new
is viewed as a Function<Object[], DeviationRisk>
by the compiler.
You can try with:
List<DeviationRisk> result = results.stream()
.map(DeviationRisk::new)
.collect(Collectors.toList())
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