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']
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']
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.
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']
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"));
}
}
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.
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.