r123454321
r123454321

Reputation: 3403

Convert ListMultimap to list of keys with duplicates?

So I have a ListMultimap<Integer, String> that I want to convert to a List<Integer> that contains duplicates of the same Integer if there was >1 value associated with a Integer key in the ListMultimap. For instance, if:

ListMultimap<Integer, String> myMap = {2 -> "foo", 3 -> ("bar1, bar2")}

I want my resultant List<Integer> to look like: [2, 3, 3]. What is the easiest way to do this?

Thanks.

Upvotes: 0

Views: 1568

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

Assuming this is Guava, this is just the one line

Lists.newArrayList(multimap.keys())

or, if you have an ImmutableListMultimap,

multimap.keys().asList()

(Note here that Multimap.keys() is a Multiset<Integer>, which iterates over elements exactly in the way you want -- that is, it will have one occurrence of each key for each value associated with that key.)

Upvotes: 4

Related Questions