Skip to content
Advertisement

How to process object with map for CSV output

I have a set of below Objects, which i need to write to CSV:

public class OutputObject {
    private String userId;
    private Map<String, Object> behaviour;
}

Above set can have a map with two, three or four values.

[
OutputObject1 [userId=11, behaviours={color=white, size=S, owner=Mr. A}], 
OutputObject2 [userId=22, behaviours={color=black, isNew=true}],
OutputObject3 [userId=33, behaviours={color=green, size=L}]
]

Output of CSV required:

userId, color, size, owner, isNew
11,     white,  S,   Mr. A,
22,     black,   ,        , true
33,     green,  L,        ,

I started with below snippet to print out:

     // Set<OutputObject> outputObjectSet already received.
     JSONArray jsonArrayObject = new JSONArray(outputObjectSet);
     String csvValue = CDL.toString(jsonArrayObject);
     FileWriter fileWriter = new FileWriter(fileObject, true);
     fileWriter.write(csvValue);
     fileWriter.close();

But above is creating a two column csv with userId and behaviours printing all map object behaviours. How to achieve above type of output.

As the set may contain huge number of such objects, how can this be done efficiently.

Advertisement

Answer

Using JSONArray seems to be redundant here, you could implement a helper method to serialize OutputObject into a CSV string, taking into account that the order of the columns needs to be maintained:

public class CSVSerializer {
    public static String transform(OutputObject obj) {
        String[] fields = {"color", "size", "owner", "isNew"};
        return Stream.concat(
                Stream.of(obj.getUserId()), 
                Arrays.stream(fields)
                      .map(f -> obj.getBehaviour().get(f))
                      .map(v -> v == null ? "" : v.toString()) 
               )
               .collect(Collectors.joining(","));
    }
}


String csv = outputObjectSet.stream()
                            .map(CSVSerializer::transform)
                            .collect(Collectors.joining("n"));
// print csv contents
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement