How to split a stream of Strings and generate a List of String-arrays?

MWB :

I am fairly new to streams, so please help me out (and be gentle).

What I would like to do is the following. I have a BufferedReader that reads from a file in which each line looks something like this: "a, b". For example:

Example Input file

"a, b"

"d, e"

"f, g"

I would like to convert this to a LinkedList<String[]>:

Example LinkedList<String[]>

[{"a", "b"}, {"c", "d"}, {"f", "g"}]

How would you do this using a stream approach?

This is what I tried:

List numbers = reader.lines().map(s -> s.split("[\\W]")).collect(Collectors.toList());

This does not work. My IDE provides the following feedback:

Incompatible types. Required List but 'collect' was inferred to R: no instance(s) of type variable(s) T exist so that List<T> conforms to List

It shows... I am still trying to figure streams out.

Ousmane D. :

Firstly, I'd suggest avoiding the use of raw types and instead, use List<String[]> as the receiver type.

List<String[]> numbers = reader.lines()
                               .map(s -> s.split(delimiter)) // substitute with your deilimeter
                               .collect(Collectors.toList());

You mentioned that you wanted a LinkedList implementation. you should almost always favour ArrayList which toList returns by default currently although it is not guaranteed to persist thus, you can specify the list implementation explcitly with toCollection:

List<String[]> numbers = reader.lines()
                               .map(s -> s.split(delimiter)) // substitute with your deilimeter
                               .collect(Collectors.toCollection(ArrayList::new));

and likewise for LinkedList:

List<String[]> numbers = reader.lines()
                               .map(s -> s.split(delimiter)) // substitute with your deilimeter
                               .collect(Collectors.toCollection(LinkedList::new));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36810&siteId=1