private static CsvFile parseAll( List<String> lines, int lineIndex, char separator, ImmutableList<String> headers, ImmutableMap<String, Integer> searchHeaders) { ImmutableList.Builder<CsvRow> rows = ImmutableList.builder(); for (int i = lineIndex; i < lines.size(); i++) { ImmutableList<String> fields = parseLine(lines.get(i), i + 1, separator); if (!fields.isEmpty()) { rows.add(new CsvRow(headers, searchHeaders, i + 1, fields)); } } return new CsvFile(headers, searchHeaders, rows.build()); }
/** * Obtains an instance from a list of headers and rows. * <p> * The headers may be an empty list. * All the rows must contain a list of the same size, matching the header if present. * * @param headers the headers, empty if no headers * @param rows the data rows * @return the CSV file * @throws IllegalArgumentException if the rows do not match the headers */ public static CsvFile of(List<String> headers, List<? extends List<String>> rows) { ArgChecker.notNull(headers, "headers"); ArgChecker.notNull(rows, "rows"); int size = (headers.size() == 0 && rows.size() > 0 ? rows.get(0).size() : headers.size()); if (rows.stream().filter(row -> row.size() != size).findAny().isPresent()) { throw new IllegalArgumentException("Invalid data rows, each row must have same columns as header row"); } ImmutableList<String> copiedHeaders = ImmutableList.copyOf(headers); ImmutableMap<String, Integer> searchHeaders = buildSearchHeaders(copiedHeaders); ImmutableList.Builder<CsvRow> csvRows = ImmutableList.builder(); int firstLine = copiedHeaders.isEmpty() ? 1 : 2; for (int i = 0; i < rows.size(); i++) { csvRows.add(new CsvRow(copiedHeaders, searchHeaders, i + firstLine, ImmutableList.copyOf(rows.get(i)))); } return new CsvFile(copiedHeaders, searchHeaders, csvRows.build()); }