Martin
Martin

Reputation: 2266

Guava: merge two multimaps

I have tree classes e.g. ClassA, ClassB, ClassC. ClassA and ClassB extends ClassC. I have two Multimaps - Multimap<Integer, ClassA> and Multimap<Integer, ClassB> and I would like to merge this two multimaps into one. I have tried find some solution but unsuccessfully. I have tried sth. like Multimap<Integer, ? extends ClassC> but I don't know if I make it right and if I can merge two multimaps together. Can someone help me? Thank you for response, I appreciate every help.

Upvotes: 6

Views: 4636

Answers (2)

jacobm
jacobm

Reputation: 14025

Multimap<Integer, ClassC> combine(Multimap<Integer, ? extends ClassC> a, Multimap<Integer, ? extends ClassC> b) {
  Multimap<Integer, ClassC> combined = new SetMultimap<Integer, ClassC>();  // or whatever kind you'd like
  combined.putAll(a);
  combined.putAll(b);
  return combined;
}

Upvotes: 8

Hari Menon
Hari Menon

Reputation: 35405

Multimap<Integer, ? extends ClassC> would mean that the generic type can be any type that extends ClassC, but the type has to be fixed. i.e, it can be either all ClassA or all ClassB. So you should use Multimap<Integer, ClassC> instead. It will accept both the types ClassA and ClassB.

Upvotes: 9

Related Questions