List<String> letters = Arrays.stream(yourString.split(" ").filter(part->part.length()==1).collect(Collectors.toList());
Step-by-step explanation:
Take your source string, split it at every blank character and put all resulting strings in a string array:
String[] parts = yourString.split(" ");
The resulting string array currently also contains strings having more than 1 character. So you have to iterate over these strings and remove all those strings that have more than 1 character, so that in the end only strings with a single character will remain. Java8 Streams API allows you to do so in a descriptive way (Stream<T> filter(Predicate<? super T> predicate)
method), so let's transform the string array to a stream of strings:
Stream<String> partsStream = Arrays.stream(parts);
Now you can filter the stream by calling Stream<T> filter(Predicate<? super T> predicate)
method on this stream - all matching strings will be returned as a new stream. Quick note on predicates: Java interface java.util.function.Predicate
is a so called 'functional interface', functional interfaces have only one boolean-valued method - in case of Predicate this single method is called boolean test(T t)
. So for every item in the stream this test(...)
method will by called to decide wether the item matches a certain condition. A short and descriptive implementation of this predicate can be a so called lambda expression (Java8+):
// for filtering in the next line, only keep strings with 1 character!
Predicate<String> filterCondition = item -> item.length() == 1;
Stream<String> filteredStream = partsStream.filter(filterCondition);
In the end you 'collect' all strings inside the filtered stream into a java.util.List
of type java.lang.String
:
List<String> letters = filteredStream.collect(Collectors.toList());