Writing data to a .CSV file using a Java 8 Stream

Viewed 5328

I am trying to output 2 collections of data to a .csv file in Java.

Collection 1 = customer names Collection 2 = customer references

I want the .csv to present as:

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:

Smith,
:Johnson,
:Collins839393,
:283940,
:293845

How can I achieve the desired output?

4 Answers

You can do this way if both lists have the same size. Use IntStream.range to iterate the lists and then map the data. Then collect joining ,\n

String res = IntStream.range(0, customers.size())
                      .mapToObj(i -> customers.get(i) + ":" + references.get(i))
                      .collect(Collectors.joining(",\n"));

Assuming both of your collections have same number of elements you can try this

String output =
        IntStream.rangeClosed(0, customers.size()-1)
            .boxed()
            .map(i -> customers.get(i) + ":" + references.get(i))
            .collect(Collectors.joining("\n"));
writer.write(output);

I assume customers and references have the same size. You can iterate between 0 and customers.size() and combine the elements of both lists:

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());

What you are trying to do is called collection zipping.

See full article here

In pure java you can do the solutions

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"));
Related