Java Convert List<String> to List<Object> -
i've 2 classess csvread , myownclass.
in csvread i've method public static list getdatafromcsv(); returns list of data. , data want take in method in class myownclass , return there list of objects of ownclass
it looks this:
list<string> datafromcsv = new arraylist<string>();
and in class, want convert list<object>
of class.
private static list<string> getdatafromcsvclass = new arraylist<string>(); getdatafromcsvclass = csvreader.getallcsvdata(filename); string name = datafromcsv[0]; string surname = datafromcsv[1]; string birth = datafromcsv[2];
i want return new myownclass(name, surname, birth);
my error: array required list found: string name = alldata[0]; etc
you can create method
convert string
myownclass
, use stream
map elements, e.g.:
public static myownclass converttoobject(string element){ string[] tokens = element.split(","); return new myownclass(tokens[0], tokens[1], tokens[2]); } //code convert list<string> datafromcsv = new arraylist<string>(); list<myownclass> list = datafromcsv.stream() .map(e -> converttoobject(e)) .collect(collectors.tolist());
however, may not work if let's name
or surname
contains comma. in case, recommend having @ opencsv
library , this example of how read csv objects.
Comments
Post a Comment