For each key in a Guava Multimap I need to take the corresponding values and make pairs with them that are not dependent on order.Uniqueness of pairs are not dependent on order for make pairs inside of key. [A,B] = [B,A]. If the pair [B,A] is found in another key then this should treated as another pair. I don't know how iterate the values so I can print out pairs that aren't dependent on order. I'm not sure how to index this either. For arrays, I could just use a double loop.
Here is an example Multimap:
BE0004429: [DB00515, DB00951, DB01582]
BE0000059: [DB00603, DB01285]
BE0001052: [DB00366, DB00472, DB00856, DB01104, DB01149]
I want to take that data and change it to this format. Look carefully, I'm trying to take the values of each key and make pairs.
I want take the first value in the each key and pair it up with the other values. Take the second value and pair it with the value after. Until there no more unique pairs.
DB00515, DB00951
DB00515, DB01582
DB01582, DB00951
DB00603, DB01285
DB00366, DB00472
DB00366, DB00856
DB00366, DB01104
DB00366, DB01149
DB00472, DB00856
DB00472, DB01104
DB00472, DB01149
DB00856, DB01104
DB00856, DB01149
DB01104, DB01149
There's two parts to this question, now that I understand it, and really the fact that you're working with Multimaps isn't very important. It's valuable to try to break problems into its component parts; when you do the problems often become clearer, even trivial seeming.
How do I print successive pairs from a collection?
We need to define a function which will take a Collection (this will let us work with arbitrary Multimaps), and generate your pairs:
public static <V> List<String> genPairs(Collection<V> col) {
List<V> ls = ImmutableList.copyOf(col);
List<String> ret = new ArrayList<>();
for (int i = 0; i < ls.size()-1; i++) {
for (int j = i+1; j < ls.size(); j++) {
ret.add(ls.get(i)+", "+ls.get(j));
}
}
return ret;
}
Demo:
for(String pair : genPairs(ImmutableList.of(1,2,3))) {
System.out.println(pair);
}
1, 2 1, 3 2, 3
How do I print successive pairs from the values of a Multimap?
This part's easy, you just loop over the value collections and call the above function:
for(Collection<String> col : multimap.asMap().values()) {
for(String pair : genPairs(col)) {
System.out.println(pair);
}
System.out.println();
}