Reputation: 428
I have a Map<String, Long>
that looks something like:
{A=1, B=2, C=3, D=4, E=3, F=2, G=1}
I want to create a new List<Set<String>>
that gets a key from the previous map and create all possible pairings with the other keys as Set<String>
and put it into the created List<String>
so that it would look something like:
[A,B], [A,C], [A,D], [A,E], [A,F], [A,G], [B,C], [B,D], [B,E], [B,F], [B,G],
[C,D], [C,E], [C,F], [C,G], [D,E], [D,F], [D,G], [E,F], [E,G], [F,G]
What is a good way for me to do it?
Upvotes: 1
Views: 195
Reputation: 24593
Using Java 11 collection methods and Streams:
var n = map.size();
var keys = new ArrayList<>(map.keySet());
var combinations = IntStream
.range(0, n)
.boxed()
.flatMap(i -> IntStream
.range(i + 1, n).mapToObj(j -> Set.of(keys.get(i), keys.get(j))))
.collect(Collectors.toList());
System.out.println(combinations);
[[B, A], [C, A], [D, A], [E, A], [F, A], [G, A], [C, B], [D, B], [E, B], [F, B], [G, B], [D, C], [E, C], [F, C], [G, C], [E, D], [F, D], [G, D], [F, E], [G, E], [G, F]]
Upvotes: 3
Reputation: 25980
Without worrying too much about efficiency:
List<String> keys = new ArrayList<String>(myMap.keySet());
List<Set<String>> keyPairs = new ArrayList<>();
for (int i = 0; i < keys .size(); i++)
for (int j = i + 1; j < keys .size(); j++)
keyPairs.add(Set.of(keys[i], keys[j]))
Upvotes: 5