Skip to content

Instantly share code, notes, and snippets.

@vi6six
Last active January 23, 2024 18:17
Show Gist options
  • Save vi6six/8e4b294cda80c3eb67a1177ce2ccc353 to your computer and use it in GitHub Desktop.
Save vi6six/8e4b294cda80c3eb67a1177ce2ccc353 to your computer and use it in GitHub Desktop.
Java 8 streams Map of maps transformation
private static void checkTreesForMissingDefinitions(Map<String, String> glossary) {
FinancialTrees.getTrees(false).values().stream() // Map<IndustryTemplate, Map<FinancialGroup, FinancialTree>>
.map(Map::values) // Stream<Collection<FinancialTree>>
.flatMap(Collection::stream) // Stream<FinancialTree>
.map(FinancialTree::getAllChildren) // Stream<List<FinancialTreeNode>> Get nodes fron tree as a List<Node>
.flatMap(List::stream) // Stream<FinancialTreeNode>
.map(FinancialTreeNode::getField) // Stream<FinField>
.distinct() // remove duplicated fields
.filter(Objects::nonNull) // remove null objects
.filter(e -> !glossary.containsKey(e.getId())) // remove fields that have a definition
.sorted() // sort
.forEach(System.out::println); // logger.log of simply print out fields without definition
// Alternatively you can .collect(Collectors.toSet()) after last filter.
}
Map<String, Map<Integer, List<Integer>>> map = ...
List<Integer> keys = map.values() // Collection<Map<Integer, List<Integer>>>
.stream() // Stream<Map<Integer, List<Integer>>>
.map(Map::keySet) // Stream<Set<Integer>>
.flatMap(Set::stream) // Stream<Integer>
.collect(Collectors.toList()); // List<Integer>
List<Integer> values = map.values() // Collection<Map<Integer, List<Integer>>>
.stream() // Stream<Map<Integer, List<Integer>>>
.map(Map::values) // Stream<Collection<List<Integer>>>
.flatMap(Collection::stream) // Stream<List<Integer>>
.flatMap(List::stream) // Stream<Integer>
.collect(Collectors.toList()); // List<Integer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment