I want to store a collection of objects that are keyed based upon a value they represent. These keys can be repeated. e.g.:
[4] => Bob
[5] => Mary
[5] => Sue
[9] => Steve
[10] => Jason
[10] => Michelle
Essentially, I want to loop through this and look at each key and say, “is there another object (person in this case) whose key is within 1 from the current key? If so, match them up and remove them from the collection.” I’m going to iterate the “1” value in the example above until the collection is empty (or has one object remaining for odd-numbered scenarios).
I’m not convinced the way I’m trying to go about this is the best way, so I’m open to feedback too.
You want a Multimap. Guava provides this interface and various subinterfaces such as
ListMultimap,SetMultimapandSortedSetMultimapdepending on what kind of collection you want values to be stored in. It then provides various implementations such asArrayListMultimapandHashMultimap, plus various utlities for use with them in Multimaps.The traditional way of doing this in Java is something like
Map<K, List<V>>,Map<K, Set<V>>etc., but maintaining the values collections is tedious and various operations that should be simple (such as just putting a value for a key) are much more complicated than they need to be.Multimapis intended as a data structure specifically designed to model multiple values mapped to a single key (unlikeMap). Given that, it makes operations as simple as you’d expect:If you wanted to ensure the same value isn’t mapped to a single key twice and don’t care about the order the values are in, you can use a
SetMultimapinstead of aListMultimap, etc.I’m not sure what you mean as far as “is there another object whose key is within 1 from the current key? If so, match them up and remove them from the collection.” But if I’m reading it right, you could do something like this:
Alternatively you could do something with a
TreeMultimap<Integer, String>which will have both its key set and value sets sorted.