Skip to content

How can I create a stream of objects?

Let’s say I have:

interface SomeInterface {       
   Foo getFoo();


class SomeClass implements SomeInterface {
    Foo getFoo() {
       //returns a Foo object

Then in a service, I have:

List<SomeClass> getItems() {
   //returns a list of SomeClass objects

It is not allowed to do the following:

Stream<SomeInterface> items = service.getItems().stream();

But ultimately, I have other classes that would share this interface and would want to do:

someMethod(Stream<SomeInterface> items) {
   //some operation

Is there a way around this? Like using flatMap? (I noticed that if I have a wrapper class on a List of SomeClass objects, I can flatMap the wrapper to return a stream of SomeInterface objects.)

I didn’t find similar questions and don’t readily see the solution. Could be something easy I’m missing. Java 14.


If your goal is to let someMethod accept Streams of SomeInterface interface along with its subtypes then you can use

/*someReturnTypeHere*/ someMethod(Stream<? extends SomeInterface> items){
   //some operation