Skip to content
Advertisement

Scanning input in HashMap of String and ArrayList

I need to add all these cities in a HashMap of String and ArrayList

I/P:    Banglore Hyderabad
        Banglore Chennai
        Hyderabad Mumbai
        Hyderabad Delhi
        Chennai Kerela

And I am unable to add these , I have the structure

import java.util.*;

public class Main {

    public static void main() {
        Scanner in = new Scanner(System.in);
        
        HashMap<String, ArrayList<String>> adj = new HashMap<String, ArrayList<String>>();
      
    }
}
       

So now i need to add banglore and then if banglore is present i will add Hyderabad to the ArrayList and again I’ll scan for the next element again banglore is present so add Chennai to the ArrayList.

There is already a question of creating a HashMap of String and ArrayList but firstly it is List of HashMap and Secondly no one there have shown how to add.

Advertisement

Answer

Try this.

static void add(Map<String, List<String>> map, String key, String value) {
    map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}

public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    add(map, "Banglore", "Hyderabad");
    add(map, "Banglore", "Chennai");
    add(map, "Hyderabad", "Mumbai");
    add(map, "Hyderabad", "Delhi");
    add(map, "Chennai", "Kerela");
    System.out.println(map);
}

output:

{Banglore=[Hyderabad, Chennai], Chennai=[Kerela], Hyderabad=[Mumbai, Delhi]}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement