Stream.of with mixed input contents

Viewed 82

I'm wondering if it would be possible to replace the following piece of code:

Object o;

// o can be one of the two following things
o = Arrays.asList("Toto", "tata", "Titi");
o = "Test";

if (o instanceof List<?>) {
    ((List<?>) o).stream().forEach(System.out::println);
} else {
    System.out.println(o);
}

By something less ugly using Stream.of. I thought of this:

Object o;

// o can be one of the two following things
o = Arrays.asList("Toto", "tata", "Titi");
o = "Test";

Stream.of(o).forEach(System.out::println);

But obviously it does not work as Stream.of(aList) does not "flatten" its contents.

Any ideas? Am I dreaming of something that does not exist?

Thanks

PS. I do not know the Object type before the forEach call. The pieces of code are just an easy example of the problem.

4 Answers
Related