I have the following data structure:
Map<Integer, Map<String,Double>>
----------------
| | a 2 |
| 100 | b 1 |
| | c 2 |
----------------
| | a 2 |
| 101 | c 2 |
----------------
| | a 2 |
| 102 | b 1 |
| | c 2 |
----------------
GOAL: get the ID of the outer map containing the inner map with the maximum size.
For example, 100
or 102
, which both contain an inner map whose size is 3.
How can I use Stream API
, for example?
map.values().stream().max(Comparator.comparingInt(Map::size)).get()
is what you're looking for.
map.keySet().stream().max(Comparator.comparingInt(k -> map.get(k).size()))
or the above if you want the key, not the map. Test code:
Map<Integer, Map<String, Integer>> map = new HashMap<>();
Map<String, Integer> map2 = new HashMap<>();
map2.put("A", 1);
map2.put("B", 2);
map2.put("C", 3);
map.put(100, map2);
map2 = new HashMap<>();
map2.put("A", 1);
map2.put("B", 2);
map.put(101, map2);
System.out.println(map.values()
.stream()
.max(Comparator.comparingInt(Map::size)).get());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With