问题描述
我有一组下面的对象,我需要将其写入CSV:
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}]
]
需要输出CSV:
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();
但是上面创建的是两列csv,其中 userId 和行为打印所有地图对象行为.如何实现上述类型的输出.
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.
推荐答案
在这里使用JSONArray似乎是多余的,考虑到列的顺序,您可以实现一个辅助方法来将OutputObject
序列化为CSV字符串.需要维护:
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
这篇关于如何处理带有地图的对象以进行CSV输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!