0

There is an existing Set<Trump> that is passed on to another function that takes in a Set<? extends Politician> as an argument. Given that 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?
    }

} 
resueman
  • 10,572
  • 10
  • 31
  • 45
user46743
  • 89
  • 1
  • 10
  • without using `instanceof` or reflection? – bradimus Nov 14 '16 at 18:41
  • 1
    Using `instanceof` can be evidence of code smell .. but ... if you don't have access to the code for the supertype, then it may be the best, quickest, cheapest option for operating upon subtype instances of a known type. – scottb Nov 14 '16 at 19:16
  • @bradimus .. yes.. To do it without reflection or instanceof.. its okay to redesign the derived class or the argument for the function.. – user46743 Nov 14 '16 at 19:17
  • @scottb I agree. Any way to change the design of derived class so that they can be identified in a collection containing base class objects and only one type of derived class objects. – user46743 Nov 14 '16 at 19:19
  • In general, if building from scratch, what would be a proper OOP way to design so as to identify sub-Types in a collection of Types? – user46743 Nov 14 '16 at 20:09
  • Ask why you need to *identify* the subtypes. Is it to perform a certain behavior on those instances? If the answer is "yes", then the proper OOP way to address this circumstance is take advantage of polymorphism so that you don't need to identify the subtype at all .... the subtype knows how to take care of itself. – scottb Nov 14 '16 at 20:14

2 Answers2

2

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.

f1sh
  • 11,489
  • 3
  • 25
  • 51
1

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());
}
Liju John
  • 1,749
  • 16
  • 19