简体   繁体   中英

Entering values inside a nested map

I was thinking of ways to implement an adjacency list for a graph and thought a nested map might be a good idea(because of the fast lookup times) for the outer map I can say map.put but for the inner map which is unnamed how do I put the values in

    Scanner sc = new Scanner(System.in);
    Map<Integer,Map<Integer,Integer>> graph = new HashMap<>();
    int V = sc.nextInt();
    int E = sc.nextInt();
    for(int i=0;i<E;i++){
        int v1 = sc.nextInt();
        int v2 = sc.nextInt();
        int w = sc.nextInt();
        graph.put(v1, Map.entry(v2, w));
        graph.put(v2, Map.entry(v1, w));

    }

where v1 and v2 are nodes/vertices of the graph and w is the weight/edge between two vertices

does anyone have any idea? thanks in advance:)

You can put into the graph like this

if (!graph.contains(v1)) {
    grah.put(v1, new HashMap<>());
}

if (!graph.contains(v2)) {
    grah.put(v2, new HashMap<>());
}

graph.get(v1).put(v2, w);
graph.get(v1).put(v2, w);
  1. Create the inner map if is absent graph.putIfAbsent(v1, new HashMap<>());
  2. Get the inner map graph.get(v1)
  3. Put the value in the inner map graph.get(v1).put(v2, 2)
graph.putIfAbsent(v1, new HashMap<>());
graph.putIfAbsent(v2, new HashMap<>());
graph.get(v1).put(v2, w);
graph.get(v2).put(v1, w);

I'm not sure where you got the Map.entry method from, but normally you'd create the inner map just like the outer one and then put it in. Something like:

Scanner sc = new Scanner(System.in);
Map<Integer,Map<Integer,Integer>> graph = new HashMap<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i=0;i<E;i++){
    int v1 = sc.nextInt();
    int v2 = sc.nextInt();
    int w = sc.nextInt();

    Map<Integer,Integer> innerMap = new HashMap<>();
    innerMap.put(v2, w);
    graph.put(v1, innerMap);

    Map<Integer,Integer> andAnotherMap = new HashMap<>();
    andAnotherMap.put(v2, w);
    graph.put(v2, andAnotherMap);

}

Of course it would be cleaner to wrap that in a method, so you would end up with:

private Map<Integer, Integer> innerMap(int a, int b) {
  Map<Integer,Integer> innerMap = new HashMap<>();
  innerMap.put(a, b);
  return innerMap;
}

...

Scanner sc = new Scanner(System.in);
Map<Integer,Map<Integer,Integer>> graph = new HashMap<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i=0;i<E;i++){
    int v1 = sc.nextInt();
    int v2 = sc.nextInt();
    int w = sc.nextInt();
    graph.put(v1, innerMap(v2, w));
    graph.put(v2, innerMap(v1, w));

}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM