Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get back list of string from an stream

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"));
like image 505
poyger Avatar asked Dec 31 '25 10:12

poyger


2 Answers

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.

like image 93
khelwood Avatar answered Jan 03 '26 00:01

khelwood


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.

like image 37
Holger Avatar answered Jan 02 '26 23:01

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!