Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - How to transform a List of arrays into a List of a specific class object

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?

like image 328
Alboz Avatar asked Jan 27 '15 13:01

Alboz


People also ask

Can you cast an array to a list?

array ] objects can be converted to a list with the tolist() function.


2 Answers

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.

like image 107
fge Avatar answered Nov 06 '22 20:11

fge


You can try with:

List<DeviationRisk> result = results.stream()
                                    .map(DeviationRisk::new)
                                    .collect(Collectors.toList())
like image 42
Konstantin Yovkov Avatar answered Nov 06 '22 21:11

Konstantin Yovkov