Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Find hash table with maximum size

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?

like image 464
Fab Avatar asked Dec 08 '22 20:12

Fab


1 Answers

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());
like image 189
xenteros Avatar answered Jan 02 '23 00:01

xenteros