I have to filter strings from a list containing lines shown below.
"15:09:00 SOME TEXT SOME TEXT 088"
"15:09 SOME TEXT 1546 AMOUNT"
"15:09:06 SOME TEXT 1546 AMOUNT"
"13:03:00 SOME TEXT TEXT TEXT 00"
I want to get elements that start with 15:09
and then split the line by white space. The split()
method returns an array.
How to collect this to an array using streams?
I've tried the code below. I don't understand how to collect the data to array, that's why here method collect()
returns a list.
String [] parts = myList.stream()
.filter(p -> p.startsWith("19:01 "))
.map(l -> l.split("\\s "))
.collect(Collectors.toList());
CodePudding user response:
split returns an array
You need to apply flatMap()
in order to produce a stream of Strings
from a stream of Strings[]
.
And in order to collect the stream data into an array, you need to apply toArray()
, which expects a function that produces an array of the desired type, as terminal operation:
public static void main(String[] args) {
List<String> myList =
List.of("15:09:00 SOME TEXT SOME TEXT 088",
"15:09 SOME TEXT 1546 AMOUNT",
"15:09:06 SOME TEXT 1546 AMOUNT",
"13:03:00 SOME TEXT TEXT TEXT 00");
String[] parts = getParts(myList, "15:09:06", "\\s ");
System.out.println(Arrays.toString(parts));
}
public static String[] getParts(List<String> source, String prefix, String delimiter) {
return source.stream()
.filter(str -> str.startsWith(prefix)) // Stream<String>
.map(str -> str.split(delimiter)) // Stream<String[]>
.flatMap(Stream::of) // Stream<String>
.toArray(String[]::new);
}
Output
[15:09:06, SOME, TEXT, 1546, AMOUNT]
CodePudding user response:
if I were in you I'll do this for to select a single char of the string, if char is equals " " use the substring metod to copy the string in an arrylist and delite the string selected from the text