将列表<Model>转换为列表<字符串[]> Java 用于使用 opencsv 写入 csv



如何放置这个listproduct

List<GetProductModel> listProduct = new ArrayList<>();

GetProductModel

private String ProductName,Description,Price; //getter and setter

到此列表

List<String[]> list = new ArrayList<>();
所以我可以把list放到
try (CSVWriter writer = new CSVWriter(new FileWriter("c:\test\monitor.csv"))) {
writer.writeAll(list);
} catch (Exception e) {
e.printStackTrace();
}

你可以使用for循环或流:

List<String[]> list = listProduct.stream()
.filter(Objects::nonNull)
.map(getProductModel -> new String[]{getProductModel.getProductName(), getProductModel.getDescription(), getProductModel.getPrice()})
.collect(Collectors.toList());
List<GetProductModel> listProduct = new ArrayList<>();
List<String[]> list = new ArrayList<>();
for(GetProductModel x : listProduct) {
String[] tmpArray = new String[3];
tmpArray[0] = x.getProductName();
tmpArray[1] = x.getDescription();
tmpArray[2] = x.getPrice();
list.add(tmpArray);
} 

使用Java流API, Lambda映射和printwwriter写入csv:

import com.opencsv.CSVWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
GetProductModel getProductModel = new GetProductModel();
getProductModel.setProductName("ProductName");
getProductModel.setDescription("Description");
getProductModel.setPrice("Price");
GetProductModel getProductModel2 = new GetProductModel();
getProductModel2.setProductName("ProductName2");
getProductModel2.setDescription("Description2");
getProductModel2.setPrice("Price2");
GetProductModel getProductModel3 = new GetProductModel();
getProductModel3.setProductName("ProductName3");
getProductModel3.setDescription("Description3");
getProductModel3.setPrice("Price3");
List<GetProductModel> getProductModels = new ArrayList<>();
getProductModels.add(getProductModel);
getProductModels.add(getProductModel2);
getProductModels.add(getProductModel3);
writeToFileUsingPrintWrite(getProductModels);
writeToFileUsingCSVWriter(getProductModels);
}
private static void writeToFileUsingPrintWrite(List<GetProductModel> getProductModels) {
List<String> productsList = getProductModels
.stream()
.map(p -> p.getProductName() + "," + p.getDescription() + "," + p.getPrice())
.collect(Collectors.toList());
File csvOutputFile = new File("C:\products.csv");
try (
PrintWriter pw = new PrintWriter(csvOutputFile)) {
productsList
.forEach(pw::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void writeToFileUsingCSVWriter(List<GetProductModel> getProductModels) {
Iterable<String[]> productsList = getProductModels
.stream()
.map(p -> new String[]{p.getProductName(), p.getDescription(), p.getPrice()})
.collect(Collectors.toList());
CSVWriter writer;
try {
writer = new CSVWriter(new FileWriter("C:\products_2.csv"));
writer.writeAll(productsList);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

最新更新