views:

125

answers:

5

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']

+2  A: 
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.

Jonathon
Oh c'mon! Give us the code heterogenous code sample!
FrustratedWithFormsDesigner
@FrusteratedWithFormsDesigner: It's the same code, but without the `<String, String>` sets. Not only that, but everything you get back out will be of type `Object`, and you'll have to cast it back to its original type.
R. Bemrose
@R. Bemrose: Boo. I was hoping for a more interesting solution than just `Object` s.
FrustratedWithFormsDesigner
@FrustratedWithFormsDesigner like what? Make an answer :)
Jonathon
Any way to do that in a single line?
sprocketonline
@sprocketonline some of it, but don't do that. Java is intentionally verbose.
Jonathon
+2  A: 

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']
uthark
A: 

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"));
    }
}
ring bearer
A: 

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.

soc
A: 

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.

tulskiy