Search code examples
javacsvjava-8streamreader

Processing a CSV File to Map<String,String[]> using Java 8


I want to collect a CSV file into a map with the map key being the first string of the row (line[0]) and the map value as a string array of the rest of the row excluding line[0].

.collect(Collectors.toMap(line ->line[0], ));

unsure what to input as the second parameter of the .toMap method to achieve this

public Map<String,String[]> readFile() {

        try {
            Path path = Paths.get("src/CSV/map.csv");
            BufferedReader reader = new BufferedReader(Files.newBufferedReader(path, Charset.forName("UTF-8")));
            return reader.lines()
                    .map(line -> line.split(","))
                    .collect(Collectors.toMap(line ->line[0], ));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }


Solution

  • Or use this:

    .collect(Collectors
       .toMap(line -> line[0], line-> Stream.of(line).skip(1).toArray(String[]::new)));