Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a stream of <Interface> objects?

Let's say I have:

interface SomeInterface {       
   Foo getFoo();
}

and

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.

like image 758
vphilipnyc Avatar asked Oct 14 '25 13:10

vphilipnyc


1 Answers

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
}
like image 69
Pshemo Avatar answered Oct 17 '25 02:10

Pshemo



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!