Using the Java 8 Stream package, I want to convert a list of arrays of a type object to a list of a specific class object. Arrays in the first list contain the field of the class loaded from the database.
This is a list of arrays of an object of the type loaded from the database:
List<Object[]> results = loadFromDB();
Each Object[] element in the list contains the fields that I want to display for 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 Object[] element present in the original results list is just a representation of the array of the DeviationRisk object
Now I know how to do this using loops of 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 threads
java arrays lambda java-8 java-stream
Alboz
source share