sriram
sriram

Reputation: 9052

How Do I Search Deeply Inside A Map, Java?

I'm very new to Java. I have written code that uses a Red Black tree :

            TreeMap test = new TreeMap();
            Map mainMap = new HashMap<>();
            Map tempMap = new HashMap<>();
            List<Integer> list = new ArrayList<>();


            tempMap.put("Visa Credit Card",447747);
            list.add(421323);
            list.add(421630);
            list.add(455451);
            list.add(469375);
            tempMap.put("Visa Debit card",list);

            tempMap.put("Master Card Credit Card",523951);
            tempMap.put("Master Debit Card",5399);

            mainMap.put("ICCI",tempMap);
            mainMap.put("Next",1234);

            test.put("Values",mainMap);

            System.out.println(mainMap);

Which is printing out the following :

{Next=1234, ICCI={Master Card Credit Card=523951, Visa Debit card=[421323, 421630, 455451, 469375], Master Debit Card=5399, Visa Credit Card=447747}}

As I have expected. But in this map, I need to search for some values in the map, say for example 455451. If doing so I should get output as :

Visa Debit card, ICCI.

Is it possible to do a search over the maps?

Thanks in advance.

Upvotes: 0

Views: 203

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503649

But in this map, I need to search for some values in the map, say for example 455451.

Basically you'll need to iterate over all key/value pairs:

for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
    if (entry.getValue().contains(targetValue)) {
        System.out.println(entry.getKey());
    }
}

Obviously that's not terribly efficient - if you need to do this a lot, you'll probably want to create a reverse map as well, and keep the two in sync.

You might also want to look at Guava's Multimap types.

Upvotes: 6

Related Questions