Davide Borrello
Davide Borrello

Reputation: 37

HashMap of HashMap-> output Problems

Having the following HashMap: HashMap <String, HashMap <Integer, ArrayList <Reservation> >> buffer; I'm going to output every single value of every single key of the two hashmaps. How can I do?

I have already written this portion of the code:

HashMap map=mod.getAllRecords();

for (Object key: map.keySet()) {
    String Date=key.toString();
    Object map2=map.get(key);

    for(Object Key : ??){//<--------------

        
    }

Upvotes: 2

Views: 121

Answers (2)

Daniel Janz
Daniel Janz

Reputation: 103

Easiest way I know is to write three for-loops - first for the key elements themselves which are already strings, second for the integers within the HashMap inside the first HashMap and third for the values inside each array of the second HashMap:

    for (String key: map.keySet()) {
        System.out.println(key);                        //prints the strings
        HashMap <Integer, ArrayList <Reservation> > map2 = map.get(key);

        for(Integer key2 : map2.keySet()){
            System.out.println(key2);                   //prints the integers
            
            for (int i=0;i<map2.get(key2).size();i++) {
                System.out.println(map2.get(key2)[i]);  //prints everything in the array
            }
        }            
    }

Upvotes: 2

WJS
WJS

Reputation: 40034

Given

Map<String, Map<Integer, List<Reservation>> map = new  HashMap<>();

You can print out all the reservations, sans map keys as follows.

map.values().stream()
       .flatMap(m->m.values().stream())
       .flatMap(List::stream)
       .forEach(System.out::println); // prints each reservation
  • the first stream, streams the inner map (values of the outer map)
  • the flatMap replaces that stream with the stream of the inner values (the lists)
  • the last flatMap streams the lists.

The above presumes that the Reservation class has overridden toString

If you want to print out all the keys too, you can do it like this. I indented the output to provide a key/value hierarchy.

map.forEach((k,v)-> {
    System.out.println(k);
    v.forEach((k1,v1)-> {
         System.out.println("         " + k1);
         v1.forEach(res->System.out.println("              " + res));
    });
});

Upvotes: 1

Related Questions