Search code examples
javacollectionshashmaphashset

How do I create a dictionary in java similar to the python dictionary and input multiple values at once?


graph = {1:{'a','b'},2:{'c','d'},3:{'e','f'},4:{'g','h'},5:{'b','d'},6:{'b','e'},7:{'a','c'},8:{'f','h'},9:{'e','g'}}

What I have done:

public class Try {
    public static void main(String[] args) {
        Set<Character> universal = new HashSet<>();
        Collections.addAll(universal, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
        // System.out.println(universal);
        HashMap<Integer, HashSet<Character>> graph =
                new HashMap<Integer, HashSet<Character>>();
        HashSet<Character> values = new HashSet<Character>();
        Collections.addAll(values, 'a', 'b');

        System.out.println(values);
        // Output : [a, b]

        graph.put(1, values);
        System.out.println(graph.get(1));
        // Output : [a, b]

        System.out.println(graph);
        // Output : {1=[a, b]}

        values.removeAll(values);
        System.out.println(graph.get(1));
        // Output : []

        // Why did the value clear out from the graph?
        System.out.println(graph);
        // Output : {1=[]}
    }
}

How do I put these values at once instead of using put() function all the time? Isn't there a better way? Also, explain the reason why clear() or remove() function usage on the variable values causes it to be removed from the variable graph. I want the structure to be mutable.


Solution

  • The following Python statement:

    graph = {1:{'a','b'},2:{'c','d'},3:{'e','f'},4:{'g','h'},5:{'b','d'},6:{'b','e'},7:{'a','c'},8:{'f','h'},9:{'e','g'}}
    

    can be implemented in Java 9+ like this:

    graph = Map.of(1, Set.of("a", "b"),
                   2, Set.of("c", "d"),
                   3, Set.of("e", "f"),
                   4, Set.of("g", "h"),
                   5, Set.of("b", "d"),
                   6, Set.of("b", "e"),
                   7, Set.of("a", "c"),
                   8, Set.of("f", "h"),
                   9, Set.of("e", "g"));
    

    The result is an immutable Map<Integer, Set<String>>, unlike Python, where the result is mutable.

    Printed, it looks like this, where order changed because the Map is a HashMap:

    {4=[g, h], 3=[e, f], 2=[c, d], 1=[a, b], 9=[e, g], 8=[f, h], 7=[a, c], 6=[b, e], 5=[b, d]}