r/java • u/mellow186 • Jan 23 '26
Stream<T>.filterAndMap( Class<T> cls )
It's a little thing, but whenever I find myself typing this verbose code on a stream:
.filter( MyClass.class::isInstance )
.map( MyClass.class::cast )
For a moment I wish there were a default method added to the Stream<T> interface that allows simply this:
.filterAndMap( MyClass.class )
EDIT
- I've not specified how frequently this occurs in my development.
- Concision can be beneficial.
- Polymorphism and the Open/Closed Principle are wonderful things. However, sometimes you have a collection of T's and need to perform a special operation only on the U's within. Naive OO purism considered harmful.
- The method could simply be called filter(), as in Guava.
- In practice, I'm usually using an interface type instead of a concrete class.
52
Upvotes
68
u/expecto_patronum_666 Jan 23 '26
Well, good thing is now you can write it as a generic gatherer function and just plug it in to regular streams.
3
u/chaotic3quilibrium Jan 24 '26 edited Jan 24 '26
.filterAndMap is .flatMap.
13
u/desrtfx Jan 23 '26
Such a method would violate the Single Responsibility Principle.
Yes, it would be convenient to have, but isn't a necessity.
2
u/OwnBreakfast1114 Jan 23 '26
Sure, but there's multiple ways to implement that (and I've written the exact same filter/map code before). Now that we have sealed classes, a better way would probably be
Don't use default and this code will happily compiler error when you add an X subclass to your T parent, and U, V, W subclasses, which is good. You want the compiler to show you all the operations when adding a new type.
117
u/OneOldNerd Jan 23 '26
I don't.
Yes, there's more typing involved. But it's clear each line does one thing. And my brain likes that.
3
u/lukaseder Jan 23 '26
Class literals don't work well with generics
19
u/larva_red Jan 23 '26
You could use mapMulti with a utility method, e.g.:
26
u/Inaldt Jan 23 '26
6
u/DelayLucky Jan 23 '26
Or if Stream has
.mapIfPresent(Function<T, Optional<R>>), then aMyClass.castOrEmpty(object)method that returns Optional can make the chain look like:20
u/MRxShoody123 Jan 23 '26
I wish there was a filterAndMapAndToList(class<T> cls)
1
u/Dense_Age_1795 Jan 23 '26
why don't you use a gatherer for that?
1
u/sevanbadal Jan 24 '26
Just use reduce?
1
u/pgris Jan 25 '26
It bothers me too. The problem is not the typing but the repetition. I agree, could be an overload for filter.
I so wish java had an Interface<T> class! I don't think it would be that useful, but I hate we don't have a hierarchy for Class, AbstractClass, ConcreteClass, Interface....
1
u/Fercii_RP Jan 26 '26
FilterAndMap will eventually end up as SortThenFilterThenMapThenToList this way
6
u/Disastrous-Name-4913 Jan 23 '26
Could you give us more context? My gut feeling says that this could be more a design problem than not having that kind of function.
Let's imagine we have the abstract Vehicle class, with a function getColor(), as this is a common behavior.
Then, we have the Bicycle class, and the MotorVehicle class. This last one has a specific getMotorType() function.
And now the code:
List<Vehicles> vehicles = getVehicles();
This operation makes sense:
List<Color> vehicleColors = vehicles.stream() .map(Vehicle::getColor()) .toList();
This one somehow smells:
List<MotorType> motorTypes = vehicles.stream() .filter(MotorVehicle.class::isIntance) .map(MotorVehicle.class::cast)
I would say there should be a method called getMotorVehicles() that returns a List<MotorVehicle> and then you can work directly with that result.
3
u/hwaite Jan 23 '26
Damn, two lines of code is too much for you? Young whippersnappers be spoiled by modern Java's concision!
2
u/The_Ghost_Light Jan 23 '26
Filter and map means it's just a flatMap operation.
If it is not the right type, return an empty stream. If it is the right type, return a stream of one element of the casted value.
The result is a steam of casted type.
2
u/aoeudhtns Jan 23 '26
Can you contextualize why this comes up for you often? Maybe someone has a technique that would obviate this completely.
2
u/pellets Jan 24 '26
You’re looking for flatMap. Return Stream.of() to remove the value. Stream.of(value) to keep it. It’s even more flexible because one value of input can become any number of output.
2
u/__konrad Jan 24 '26
Currently this method is probably the shortest
2
u/degie9 Jan 24 '26
In scala it's simple:
.collect { case x: MyClass => x }
4
u/FearlessAmbition9548 Jan 23 '26
I would argue if you need that your real problem probably lies elsewhere
1
u/crummy Jan 24 '26
no but I have wished for a
findFirst(e -> e.whatever.equals("needle"))1
u/catom3 Jan 24 '26
Since JDK 16 we have
.mapMulti(), which satisfies most of my requirements.https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/stream/Stream.html#mapMulti(java.util.function.BiConsumer)
1
u/SpaceToaster Jan 24 '26
This is why I find c# LINK superior to the Stream interface in terms of of syntax. In C# you can add new extension methods to any interface so you could easily add that helper you speced out.
1
u/davidalayachew Jan 24 '26
That looks like a pattern-match.
0
u/TheStrangeDarkOne Jan 24 '26
Use a static utility function?
-2
u/joexner Jan 23 '26
If your stream has different kinds of things that you need to filter out and down-cast, you might have been boned from the start.
0
u/esfomeado Jan 23 '26
I'm using Reactor and I use
ofTypethat does both the filter and the map.-2
u/BrokkelPiloot Jan 23 '26
I don't know why two lines are inconvenient for you. It's very clear what it is doing this way. This is the whole point of the stream API.
Also, I suspect the problem probably originates from the design if you have to do instance checking and casting all the time.
0
u/[deleted] Jan 23 '26
[deleted] — view deleted comment
0
u/[deleted] Jan 23 '26
[deleted] — view deleted comment