/** * Obtains a sub-row, containing a selection of fields by index. * * @param startInclusive the start index, zero-based, inclusive * @param endExclusive the end index, zero-based, exclusive * @return the sub row */ public CsvRow subRow(int startInclusive, int endExclusive) { return new CsvRow( headers.subList(Math.min(startInclusive, headers.size()), Math.min(endExclusive, headers.size())), lineNumber, fields.subList(startInclusive, endExclusive)); }
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()); }
/** * Checks whether there is another row in the CSV file. * * @return true if there is another row, false if not * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ @Override public boolean hasNext() { if (nextRow != null) { return true; } else { String line = null; while ((line = Unchecked.wrap(() -> reader.readLine())) != null) { currentLineNumber++; ImmutableList<String> fields = CsvFile.parseLine(line, currentLineNumber, separator); if (!fields.isEmpty()) { nextRow = new CsvRow(headers, searchHeaders, currentLineNumber, fields); return true; } } return false; } }