I have an stream that contains Strings and list of Strings and I want to get out all values as List of Strings. Anyway to do this with some stream operation ?
Stream stream = Stream.of("v1", Arrays.asList("v2, v3"));
Normally you don't mix up such different types in a list, but you can get the result you want from this; each single string can be converted to a stream of one string, and each list of strings can be converted to a stream of multiple strings; then flatMap will flatten all the streams to one single stream of strings.
List<String> strings = l.stream()
.flatMap(o -> {
if (o instanceof List) {
return ((List<String>) o).stream();
}
return Stream.of((String) o);
})
.collect(Collectors.toList());
You'll get an unchecked cast warning, but that's what you get for mixing up different types in one container.
If you want to avoid “unchecked” warnings, you have to cast each element, which works best when you perform it as a subsequent per-element operation, after the flatMap step, when the single String elements and List instances are already treated uniformly:
List<Object> list = new ArrayList<>();
list.add("v1");
list.add(Arrays.asList("v2","v3"));
List<String> strings = list.stream()
.flatMap(o -> o instanceof List? ((List<?>)o).stream(): Stream.of(o))
.map(String.class::cast)
.collect(Collectors.toList());
But, as already said by others, not having such a mixed type list in the first place, is the better option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With