There is an existing Set<Trump>
that is passed on to another function that takes in a Set<? extends Politician>
Set<? extends Politician>
as an argument. Given that Set<? extends Politician>
Set<? extends Politician>
is going to contain either a Politician
Object or a Trump
Object only.
The Politican
Class can't be modified. The Trump
Class is available for modification.
Is there a way to cleanly do the following, or how should the derived class ( Trump
) be re-designed to be able to do this?
public Set<Trump> getSetOfTrump(Set<? extends Politician> politicianSet)
{
//do some processing
for(Politician pol : politicianSet){ //compiler is ok.. but I dont need Politician Object here
}
for(Trump t : politicianSet){ // any way to get Trump Objects out of politicianSet?
}
}
You'll have to filter the objects manually:
for(Politician t : politicianSet){ // any way to get Trump Objects out of politicianSet?
if(t instanceof Trump) {
//do your magic here
}
}
The instanceof
operator returns true if t
is an instance of (a subclass of) Trump.
Below code would work -
public Set<Trump> getSetOfTrump(Set<? extends Politician> politicians){
return politicians.stream().filter( s -> s instanceof Trump).map(s ->(Trump)s).collect(Collectors.toSet());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.