Dejell
Dejell

Reputation: 14317

Filtering collection with generics in java

I have the following type of collection:

Collection<GenericMessage<Collection<Client>>>;

Collection<GenericMessage<Client>>;

Collection<GenericMessage<SearchResponse<Client>>>;

and a Collection<Client> filteredClients.

I get an Object:

Collection<GenericMessage<?>> resObject = (Collection<GenericMessage<?>>) response.getEntity();

I need to filter from response object, which could be one of the above collection type, the clients that do not appear in filteredClients.

Is there a clean way to do it?

GenericMessage looks like this:

public class GenericMessage<T> {
   T object;

   public T getObject(){
    return object;
   }
   public void setObject(T object){
    this.object = object;
   }
}

Client looks like this:

public class Client extends Base

SearchResponse looks like this:

public class SearchResponse<T> extends Base{
   List<T> results;

   public List<T> getResults() {
        return results;
   }

    public void setResults(List<T> results) {
        this.results = results;
   }
}

Upvotes: 4

Views: 156

Answers (2)

John B
John B

Reputation: 32949

 if (!resObject.isEmpty()){
      GenericMessage<?> firstMessage = resObject.iterator().next();
      Object first = firstMessage.getObject();
      if (first instanceof Client){
         // do Client stuff
      }else if (first instanceof SearchResponse){
         // do SearchResponse
      }else if (first instanceof Collection){
         // blah
      }else{
         // error?
      }
 }

Upvotes: 2

darijan
darijan

Reputation: 9775

What John B wrote or adding the class type parameter to the GenericMessage class.

Something like:

GenericMessage(Class<?> type) {
    this.type= type;
}

public Class<?> getType() {
    return type;
}

And later on, you can filter on this value:

if (getType().equals(Client.class)) {
   ... //do whatevs
} else if ...

Upvotes: 0

Related Questions