Updated to use Streams in convertToCSV for BAEL-2499
This commit is contained in:
parent
bbb4016885
commit
2db589c5b4
|
@ -1,18 +1,14 @@
|
|||
package com.baeldung.csv;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class WriteCsvFileExample {
|
||||
|
||||
public String convertToCSV(String[] data) {
|
||||
StringBuilder csvLine = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
if (i > 0) {
|
||||
csvLine.append(",");
|
||||
}
|
||||
csvLine.append(escapeSpecialCharacters(data[i]));
|
||||
}
|
||||
|
||||
return csvLine.toString();
|
||||
return Stream.of(data)
|
||||
.map(this::escapeSpecialCharacters)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public String escapeSpecialCharacters(String data) {
|
||||
|
|
|
@ -65,7 +65,7 @@ public class WriteCsvFileExampleUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenBufferedWriter_whenWriteLine_thenOutputCreated() {
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
|
Loading…
Reference in New Issue