natz
natz

Reputation: 731

Nested Object Transformation using Stream API Java 8

I have a Class like this to store APIResponse from REST-API call

class DataSet {
        public String ID;    
        List<DataPoint> dataPoints;
}

class DataPoint{
       DateTime timeStamp;
       Double value;
}

What I have is an ArrayList of DataSet and need to transform into something like this

[{x: timestamp1, y: value1}, {x: timestamp2, y: value2},... {x: timestampn, y: valuen}]

for each element in the ArrayList.

I am learning Stream API of Java 8 and wish to do it using the same. Would like to know how to arrive at the output using lambda expressions of Stream API java 8.

Currently the desired output is being acheived by traditional way of using for-each which is:

List<ArrayList<Map<String, Object>>> transformedObject = new List<ArrayList<Map<String, Object>>>();
        for(DataSet m : apiResponseArray){  
            ArrayList<Map<String, Object>> dataobj = new ArrayList<Map<String, Object>>();      
            List<DataPoint> listData =m.getdataPoints();
            for(DataPoint d : listData)
            {
                Map<String, Object> dataMap = new LinkedHashMap<String, Object>();                  
                dataMap.put("x", d.getTime(););
                dataMap.put("y", d.getValue());
                dataobj.add(dataMap);
            }
            transformedObject.add(dataobj);         
        }
Gson gson = new Gson();
return gson.toJson(transformedObject);

Thanks in advance!!!

Upvotes: 2

Views: 1517

Answers (1)

rejthy
rejthy

Reputation: 446

One possible way with inner stream (if you really want list of list of map :) )

private Map<String, Object> map(DataPoint dataPoint) {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("x", dataPoint.timeStamp);
    map.put("y", dataPoint.value);
    return map;
}


List<List<Map<String, Object>>> transformedObject = dataSets.stream()
            .map(
                    dataSet -> dataSet.dataPoints.stream()
                        .map(this::map)
                        .collect(Collectors.toList())
                )
            .collect(Collectors.toList());

Upvotes: 3

Related Questions