How to split a stream of Strings and generate a List of String-arrays?
Supposing that each line is a tuple of 2 elements you could collect them into a List of something that looks like a tuple of 2 elements. Note that Java doesn't have native type for tuples (like Scala or python), so you should choose a way to represent the elements.
you could create a list of entry :
List<Map.Entry<String, String>> numbers =
reader.lines()
.map(s -> s.split(","))
.map(a -> new AbstractMap.SimpleEntry<>(a[0], a[1]))
.collect(Collectors.toList());
or a list of String :
List<String> numbers = reader.lines()
.map(s -> s.split(","))
.map(a -> "{" + a[0] + "," + a[1] + "}"))
.collect(Collectors.toList());
Note that generally, you don't want to stick to a specific list implementation as you collect the stream while in some cases you can need. In this case, specify the collection supplier to use with
toCollection(LinkedList::new)
instead of toList()
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));
You may do it like so,
Path path = Paths.get("src/main/resources", "data.txt");
try (Stream<String> lines = Files.lines(path)) {
List<String> strings = lines.flatMap(l -> Arrays.stream(l.split(","))).map(String::trim)
.collect(Collectors.toCollection(LinkedList::new));
}
Read each line of the file, then split it using the delimiter. After that trim it to eliminate any remaining white space characters. Finally collect it to a result container.