I have a
Map<String>,Set<String>> followingMap
key="john", value=Set["robert","andrew,"amanda"].
key="robert", value=Set["john"]
key="andrew", value=Set["john"]
key="amanda", value=Set["john"]
key="alex",Set["amanda"]
Map<String,Set<String>> followerGraph = new HashMap<String,Set<String>>();
for (Map.Entry<String, Set<String>> me : followsGraph.entrySet()) {
String key = me.getKey();
Set<String> tmp = new LinkedHashSet<>();
Set<String> valueSet = me.getValue();
for (String s : valueSet) {
if (followerGraph.containsKey(s)){
followerGraph.get(s).add(key);
} else {
tmp.add(key);
followerGraph.put(s, tmp);
}
}
}
{aliana=[@jake, @john, @erick], alyssa=[@john, @erick],
bbitdiddle=[@rock-smith, @john, @erick], casus=[@daniel, @jake, @john, @erick],
david=[@dude, @john]}
{@daniel=[casus], @rock-smith=[bbitdiddle], @jake=[aliana, alyssa, bbitdiddle, casus, david], @dude=[david], @john=[aliana, alyssa, bbitdiddle, casus, david], @erick=[aliana, alyssa, bbitdiddle, casus, david]}
You can do something like that:
Map<String, Set<String>> followerMap = new HashMap<>();
followingMap.forEach((name,followingSet)-> followingSet.forEach(
follower-> followerMap.computeIfAbsent(follower, f->new HashSet<>())
.add(name)));
followingMap.forEach
process all the entries in the followingMap. Then the Set of each entry is being processed with followingSet.forEach
. The elements of this set are the followers, the keys of the new map. computeIfAbsent
is being used to put a new entry in the map if it doesn't exists, adding an empty Set in that case. Afterthat, the value is added to the Set, in that case the entry of the followerMap.
And this is the same code using for
loops instead of forEach
, probably more readable.
Map<String, Set<String>> followerMap = new HashMap<>();
for (Entry<String, Set<String>> followingEntry : followingMap.entrySet()) {
for (String follower : followingEntry.getValue()) {
followerMap.computeIfAbsent(follower, s->new HashSet<>()).add(followingEntry.getKey());
}
}