Created
June 21, 2016 17:20
-
-
Save barafael/291cd55f3a5c839247b65d6d66c9610c to your computer and use it in GitHub Desktop.
Stream monstrosity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static Map<Integer, List<Integer>> makeFriendlists(List<Map<String, List<Integer>>> hashes) { | |
Map<Integer, List<Integer>> result = new ConcurrentHashMap<>(); // concurrent put might happen in parallelstream | |
// 1.: parallel stream all maps in list | |
// 2.: parallel stream all entries in entrysets of hashes | |
// 3.: for each entry in streamed hash, add it to the index list | |
hashes.parallelStream().map(hashmap -> hashmap.entrySet().parallelStream()) | |
.forEach(entries -> entries.forEach(e -> { | |
List<Integer> friends = e.getValue(); | |
for (Integer index : friends) { | |
if (result.containsKey(index)) { | |
List<Integer> indices = result.get(index); | |
// add each index in friends to indices, except index(which might occur more than once) | |
friends.stream().filter(i -> !i.equals(index)).forEach(indices::add); | |
} else { | |
List<Integer> indices = new ArrayList<>(); | |
friends.stream().filter(i -> !i.equals(index)).forEach(indices::add); | |
result.put(index, indices); | |
} | |
} | |
} | |
)); | |
result.entrySet().parallelStream().map(Map.Entry::getValue).forEach(Collections::sort); // sort each friendlist | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment