S.Niccolo
S.Niccolo

Reputation: 21

How to add contents of this stream into a linked list?

I need to read from a CSV file and add the contents into a linked list, so that I can search for a certain bit of data. At the moment the results of the CSV are fed into a stream, but I don't know how to put this into a linked list. My code is as follows:

    String fileName = "Catalogue.csv";
    LinkedList<String>catalogue = new LinkedList();

    try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

                stream.forEach(System.out::println);

    } catch (IOException e) {
        e.printStackTrace();
    }

Upvotes: 2

Views: 586

Answers (2)

dehasi
dehasi

Reputation: 2773

If you need exactly LinkedList, you can just collect your stream:

stream.collect(Collectors.toCollection(LinkedList::new));

Or, if list is already created:

stream.forEach(catalogue::add);

Upvotes: 1

Parijat Purohit
Parijat Purohit

Reputation: 921

Something like the following one liner should work:

catalogue = stream.collect(Collectors.toCollection(LinkedList::new));

You can refer to the Collectors doc here and LinkedList doc here. As mentioned in the comments above, I wouldn't advice you to unnecessarily use LinkedList in this case though as it will make your code that follows a little slower.

Upvotes: 1

Related Questions