I have a POJO as follows:
public class TestDto{
private String columnA;
private String columnB;
private String columnC;
private String columnD;
...//...//
}
DB returns me a list of TestDto;
List<TestDto> dto = //resultsList from DB.;
The parameters in TestDto may be columnA,columnB,columnC,columnD,......columnCE,columnCF....it's dynamic.
I want to convert list of TestDto to list of String array using lambda and then iterate the list and string array and assign the values to cell in excel.
I tried below but this didnt work.
List<String> stringList = dto.stream().map(Object::toString).collect(Collectors.toList());
for(int i=0; i<stringList.size(); i )
{
System.out.println("stringlist..." stringList.get(i));
}
The output that gets printed is TestDto
object but not string[]
.
I want to convert List<TestDto>
to List<String[]>
and then do the foll.
List<TestDto> listTestDto =...;
String[] stringArray = null;
for(int i=0; i<listTestDto.size(); i )
{
stringArray = listTestDto.get(i);
for(int j=0; j< stringArray.length; j ){
System.out.println("stringArray - " stringArray[i]);
}
}
Data: List:
columnA:1, columnB:ABC, columnC: 11111, columnD :null.....
columnA:2, columnB:DEF, columnC: 22222, columnD :null.....
columnA:3, columnB:GHI, columnC: 33333, columnD :null.......
columnA:4, columnB:JKL, columnC: 44444, columnD :null......
Output:
stringArray - 1
stringArray - ABC
stringArray - 11111
stringArray - null
stringArray - 2
stringArray - DEF
stringArray - 22222
stringArray - null
stringArray - 3
stringArray - GHI
stringArray - 33333
stringArray - null
stringArray - 4
stringArray - JKL
stringArray - 44444
stringArray - null
USeCase:
1. output is List<TestDto>
2. output is List<Object[]>
CodePudding user response:
You need a transformer method toStringArray
for TestDto
Add toStringArray
method to TestDto
public class TestDto {
private String columnA;
private String columnB;
private String columnC;
private String columnD;
...//...//
public String[] toStringArray() {
return new String[] { columnA, columnB, columnC, columnD,... };
}
}
Use map
operator from stream
and pass transformer method reference
List<String[]> output = list.stream().map(TestDto::toStringArray).collect(Collectors.toList());
Test your output
// Test output
for (int i = 0; i < output.size(); i ) {
System.out.println(Arrays.toString(op.get(i)));
}
CodePudding user response:
If TestDto
has dynamic fields, that is, its structure is undefined, and the entire TestDto can be represented as a map Map<String, String>
.
Therefore, the list of TestDto
is changed into the list of maps List<Map<String, String>>
, which can be transformed into List<String[]>
where each string array stores map values:
List<Map<String, String>> listTestDto =...; //
List<String[]> strings = listTestDto
.stream() // Stream<Map<String, String>>
.map(Map::values) // Stream<Collection<String>>
.map(v -> v.toArray(new String[0]))
.collect(Collectors.toList());