Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a dictionary with a specific set of data cleanly in Java

I am curious how I can more effectively instantiate a dictionary in Java. At present I have passable code, yet I am filling it with data in a very obfuscated fashion.

Is there any way for me to initialize my dictionary similar to this? This is python for the record:

westernCanadaAdjList =  {  'BC': ['AB'],
                       'AB': ['BC', 'SK'],
                       'SK': ['AB', 'MB'],
                       'MB': ['SK']
                        }

I find for presentation purposes that is a whole lot more clear.

My current code in Java:

public class Main {

public static void main(String[] args) {

    //Adjacency List representation through a dictionary. Allows fast O(1) lookup time.
    Map<String,ArrayList<String>> adjList = new HashMap<String,ArrayList<String>>();


    //Adding values for Edmonton
    adjList.put("Edmonton", new ArrayList<String>());
    adjList.get("Edmonton").add("Neighbour1");
    adjList.get("Edmonton").add("Neighbour2");
    adjList.get("Edmonton").add("Neighbour3");


    //Adding values for Vancouver
    adjList.put("Vancouver", new ArrayList<String>());
    adjList.get("Vancouver").add("V neighbour1");
    adjList.get("Vancouver").add("V neighbour2");

    System.out.println(adjList.keySet() +" And Values " +  adjList.values());

    for (String neighbour: adjList.get("Edmonton")){
        System.out.println(neighbour);
    }

    for (String neighbour: adjList.get("Vancouver")){
        System.out.println(neighbour);
    }
  }
}

Thank you very much!

like image 536
NeuralCode Avatar asked Jan 26 '16 02:01

NeuralCode


People also ask

What is the correct way to initialize a dictionary?

Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.

How do you initialize a dictionary using only the keys?

Summary: The most Pythonic approach to initialize a dictionary with keys is to use the dict. fromkeys(key, None) dictionary method, which accepts each item from the given list as a key and associates None to each key as a value. Problem Formulation: Given a list containing employee IDs as items within it.


1 Answers

Note: The original answer is over 8 years old and Java has come a long way since then. As of now I'd recommend:

var map = Map.of(
    "BC", List.of("AB"),
    "AB", List.of("BC", "SK"),
    "SK", List.of("AB", "MB"),
    "MB", List.of("SK")
);

This is the best technique I know of:

    Map<String, String> myMap = new HashMap<String, String>() {{
        put("foo", "bar");
        put("key", "value");
        //etc
    }};

Note the double braces -- this is commonly called double brace initialization.

What you're actually doing is creating an anonymous inner class that extends HashMap, and your new subclass contains an initializer block, in which you can call any arbitrary code that is guaranteed to be executed before the instance can be used.

Also note the 'diamond operator' cannot be used with anonymous classes, for whatever reason.

This is a nice technique for test classes, but I tend to avoid it for production code.

EDIT: Thought I should answer your actual question!

double-brace initialization is probably the best solution in "pure" Java, your Map would specifically look like:

    Map<String, List<String>> westernCanadaAdjList = new HashMap<String, List<String>> () {{
        put("BC", new ArrayList<String>(){{ add("AB"); }});
        put("AB", new ArrayList<String>(){{ add("BC"); add("SK"); }});
        put("SK", new ArrayList<String>(){{ add("AB"); add("MB"); }});
        put("MB", new ArrayList<String>(){{ add("SK"); }});
    }};

... Still not super awesome. Java really does need a Map literal, and it does not have one.

For production code, I'd use a Guava's MultiMap, but honestly populating it with literals isn't much better:

    Multimap<String, String> multimap = ArrayListMultimap.create();
    multimap.put("BC", "AB");
    multimap.put("AB", "BC");
    multimap.put("AB", "SK");
    multimap.put("SK", "SK");
    multimap.put("SK", "SK");
    multimap.put("SK", "SK");
like image 85
romacafe Avatar answered Oct 16 '22 16:10

romacafe