I am trying to create a csv file with the headers coming from a map and the values coming from an object. I have a Java object which stores different attribute data.
public class MyObject {
private String name;
private String email;
private Integer id;
private String phone;
getters and setters...
}
I have a Map where the user has key value pair, where the key is the attribute name of MyObject and the value is column headers for a csv file. Ex:
Map<String, String> columnMap = new HashMap<>();
columnMap.put("id", "Id");
columnMap.put("name", "User Name");
columnMap.put("email", "User Email");
columnMap.put("phone", "User Phone");
My goal is to create a csv file from the data for which I first want to retrieve the values from the map to set as headers and then create rows based on what is stored in MyObject class. Ex:
public class CopyMapToSBForFile {
public static void main(String[] args) {
List<MyObject> myObjects = new ArrayList<>();
MyObject myObject1 = new MyObject();
myObject1.setId(1);
myObject1.setName("Name 1");
myObject1.setEmail("Email 1");
myObject1.setPhone("111-121-2121");
MyObject myObject2 = new MyObject();
myObject2.setId(2);
myObject2.setName("Name 2");
myObject2.setEmail("Email 2");
myObject2.setPhone("111-121-2121");
MyObject myObject3 = new MyObject();
myObject3.setId(3);
myObject3.setName("Name 3");
myObject3.setEmail("Email 3");
myObject3.setPhone("111-121-2121");
myObjects.add(myObject1);
myObjects.add(myObject2);
myObjects.add(myObject3);
Map<String, String> columnMap = new HashMap<>();
columnMap.put("id", "Id");
columnMap.put("name", "User Name");
columnMap.put("email", "User Email");
columnMap.put("phone", "User Phone");
Field[] fields = MyObject.class.getDeclaredFields();
StringBuffer sb = new StringBuffer();
for (Field field : fields) {
System.out.println(field.getName());
if (columnMap.containsKey(field.getName())) {
sb.append(columnMap.get(field.getName()));
sb.append(",");
}
}
}
}
From the above example you can see using reflection utils I am able to create the header object but I am stuck on how to append the values from MyObject to the StringBuffer object to create something like the below output:
User Name,User Email,Id,User Phone
Name 1,Email 1,1,111-121-2121
Name 2,Email 2,2,111-121-2121
Name 3,Email 3,3,111-121-2121
I have a code which will conver the StringBuffer to CSV but I am stuck on how to create the above output once I create the header. Also, I want to make sure the program handles the row correctly incase the order of the columns are changed where the Id is first column instead of third column.
StringBuilderis preferred overStringBuffer, unless you are running multiple threads. And you might also consider using a constructor to facilitate creatingMyObjectinstances.MyObjects, which doesn't make a lot of sense. This seems like a giant XY Problem - what are you trying to do ultimately?