I am writing a function that will create an object with data. So far I get objects with data but individually not as a collection. I would like to return an object with all designated data as one Student object, not just one input for every object. I tried to add objList.add(obj) out of the for loop too and outputs all null. Here is the code
class Student{
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
public static List<Object> createObject(Student st, List<Map<String, String>> csvStudentData) {
List<Object> objList = new ArrayList<>();
Object obj = null;
for(Map<String, String> studentData: csvStudentData) {
for (Map.Entry<String, String> entry = studentData.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
obj = insertObjectData(st.getClass(), key, value);
objList.add(obj);
}
}
return objList;
}
You modify the method's body by the following:
public static List<Object> createObject(Student st, List<Map<String, String>> csvStudentData) {
List<Student> objList = new ArrayList<>();
for(Map<String, String> studentData: csvStudentData) {
Student student = new Student();
for (Map.Entry<String, String> entry = studentData.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
Field field = Student.class.getDeclaredField(key);
student.set(field, value);
}
objList.add(student);
}
return objList;
}
you also add a default constructor in the class Student
You can do it in java-8 stream
List<Object> objList = csvStudentData.stream()
.flatMap(map->map.entrySet()
.stream()
.map(entry->insertObjectData(st.getClass(), entry.getKey(), entry.getValue())))
.collect(Collectors.toList());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.