[英]Writing data to a .CSV file using a Java 8 Stream
I am trying to output 2 collections of data to a.csv file in Java.我正在尝试将 output 2 collections 的数据写入 ZD52387880E1EA22817AZ72D7 中的 a.csv 文件
Collection 1 = customer names Collection 2 = customer references集合 1 = 客户名称 集合 2 = 客户参考
I want the.csv to present as:我希望 .csv 呈现为:
Smith:839393,
Johnson:283940,
Collins:293845
My code:我的代码:
private void writeDataToFile() throws IOException {
FileWriter writer = new FileWriter("src/test/resources/custData.csv");
List<String> customers = new ArrayList<>(customers);
List<String> references = new ArrayList<>(references);
String collect1 = customers.stream().collect(Collectors.joining(",\n" + ":"));
String collect2 = references.stream().collect(Collectors.joining(",\n" + ":"));
writer.write(collect1 + collect2);
writer.close();
}
My output:我的 output:
Smith,
:Johnson,
:Collins839393,
:283940,
:293845
How can I achieve the desired output?如何实现所需的 output?
You can do this way if both lists have the same size.如果两个列表的大小相同,您可以这样做。 Use
IntStream.range
to iterate the lists and then map the data.使用
IntStream.range
迭代列表,然后使用 map 数据。 Then collect joining ,\n
然后收集加入
,\n
String res = IntStream.range(0, customers.size())
.mapToObj(i -> customers.get(i) + ":" + references.get(i))
.collect(Collectors.joining(",\n"));
I assume customers
and references
have the same size.我假设
customers
和references
具有相同的大小。 You can iterate between 0 and customers.size()
and combine the elements of both lists:您可以在 0 和
customers.size()
之间迭代并组合两个列表的元素:
customers.get(i) + ":" + references.get(i) + ",\n"
Try this:尝试这个:
String output = IntStream.range(0, customers.size()).boxed()
.map(i -> customers.get(i) + ":" + references.get(i) + ",\n").collect(Collectors.joining());
Assuming both of your collections have same number of elements you can try this假设你的两个 collections 有相同数量的元素,你可以试试这个
String output =
IntStream.rangeClosed(0, customers.size()-1)
.boxed()
.map(i -> customers.get(i) + ":" + references.get(i))
.collect(Collectors.joining("\n"));
writer.write(output);
What you are trying to do is called collection zipping.您正在尝试做的事情称为集合压缩。
In pure java you can do the solutions在纯 java 你可以做的解决方案
IntStream.range(0, Math.min(customers.size(), references.size()))
.mapToObj(i -> customers.get(i) + ":" + references.get(i))
.collect(Collectors.joining(",\n"));
If you have guava you can do it bit nicer如果你有番石榴,你可以做得更好
Streams
.zip(customers.stream(), references.stream(), (customer, reference) -> customer + ":" + reference)
.collect(Collectors.joining(",\n"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.