2

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);
        }

2 Answers 2

2

Or use this:

.collect(Collectors
   .toMap(line -> line[0], line-> Stream.of(line).skip(1).toArray(String[]::new)));
Sign up to request clarification or add additional context in comments.

2 Comments

if you're going to use a stream then this would be better IMO --> Arrays.stream(line, 1, line.length).toArray(String[]::new)
thanks for the suggestions, not encountered a stream inside a stream before
1

use Arrays.copyOfRange:

.collect(Collectors.toMap(line -> line[0], line->Arrays.copyOfRange(line, 1, line.length)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.