Search code examples
javaflat-file

Flatten two lists to be in String .csv style Format


I have two lists a List<String> headers and a List<Row> rows which is essentially a List<List<String>> I'm trying to flatten these lists to get this desired output:

Name,ID,Value
John Doe,1111,XXX
Jane Doe,2222,YYY

I'm currently using in iterator to go over the headers list and appending them to a String builder as so

        List<String> headers = ((RowListResult) result).getHeaders();
        List<RowListResult.Row> rows = ((RowListResult) result).getRows();

        output = output.concat(String.join(",", headers)).concat("\n");
        for(RowListResult.Row row: rows) output = output.concat(String.join(",", row.getColumns().toString()).concat("\n")).replace("/[[]]/", "");

        System.out.println(output);
        return null;
    }
}

I was going to do the same thing for the rows, however I feel like I am making this way harder then I should be and at the end I'd have to remove the commas at the end of each row. Is there a better way to accomplish this? A nudge in the right direction would be helpful. I can also share anything else you may need just leave a comment.

Data: Data in Debugger

Name,ID,Value
[John Doe, 1111, XXX]
[Jane Doe, 2222, YYY]

Solution

  • You can use String.join():

    import java.util.Arrays;
    import java.util.List;
    
    class Main {
      public static void main(String[] args) {
        List<String> headers = Arrays.asList("header1","header2","header3");
    
        List<String> row1 = Arrays.asList("cell1","cell2","cell3");
        List<String> row2 = Arrays.asList("cell1","cell2","cell3");
        List<List<String>> rows = Arrays.asList(row1, row2);
    
        System.out.println(toString(headers, rows));
      }
    
      private static String toString(List<String> headers, List<List<String>> rows) {
        StringBuilder str = new StringBuilder();
        str.append(String.join(", ", headers)).append("\n");
        for (List<String> row: rows) str.append(String.join(", ", row)).append("\n");
        return str.toString();
      }
    }