Tutorial :Is there a Java equivalent of Python's dictionary display?



Question:

In Python I'm using a dictionary display:

myAnonDict = {'foo': 23, 'bar': 'helloworld'}  

Is there an equivalent in Java?

[edited 'anonymous dictionary' to read 'dictionary display']


Solution:1

Map<String, String> myMap = new HashMap<String, String>();  myMap.put("foo", "23");  myMap.put("bar", "helloworld");  

This is different from yours because yours has heterogeneous data types whereas mine deals in Strings only. You can actually have mixed collections in Java, too, but I hate doing that. Kind of defeats the purpose of strong typing.


Solution:2

Apache commons lang will allow you to do something similar (a string based example; can be customized)

Here is the code:

import java.util.Map;  import org.apache.commons.lang.ArrayUtils;    public class ArrayToMapExample {        public static void main(String[] args) {          Map dict = ArrayUtils.toMap(new String[][]{{"United States", "New York"},                              {"United Kingdom", "London"},                                {"Netherland", "Amsterdam"},                                {"Japan", "Tokyo"},                                {"France", "Paris"}});              System.out.println("Capital of France is " + dict.get("France"));      }  }  


Solution:3

Java doesn't have anonymous dict because 1) it is statically-typed language, 2) it doesn't have support this feature on the syntax level. You need to specify type of the dictionary during creation. In contrast, Groovy, which is JVM-based language has this feature. You can write above code in the following way in Groovy:

def myAnonDict = [foo: 23, bar: 'helloworld']  


Solution:4

Closest shortcut to this form is the following hack:

Map<String, Object> map = new HashMap<String, Object>() {{      add("foo", 23);      add("bar", "hello")  }};  

However, this will create an anonymous class which is not always good.

Unfortunately, java is not a language of shortcuts.


Solution:5

If the question was broadened from "Java" to "language running on the Java VM", this Scala code is quite concise:

def myAnonDict = Map("foo" -> 23, "bar" -> "helloworld")  

One improvement over the Python syntax is that it is more readable to outsiders.


Solution:6

AbacusUtil, a general programming library in Java, which provides a lot of most daily used methods to make programming with Java more fun and more productivity:

    Map<String, Integer> map = asMap("abc", 23, "bar", 7);  

(Declaration: I'm the developer of AbacusUtil)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »