Is there a Java equivalent of Python mapping?

In Python, I use a dictionary display:

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

Is there an equivalent in Java?

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

+3
source share
6 answers
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("foo", "23");
myMap.put("bar", "helloworld");

This is different from yours because you have heterogeneous data types, whereas my transactions are made only in Lines. You may actually have mixed collections in Java, but I hate doing it. The type of lesion is the goal of strong typing.

+8
source

Apache commons lang will allow you to do something similar (string based example, configurable)

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"));
    }
}
+5

Java dict, 1) , 2) . . , Groovy, JVM- . Groovy:

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

:

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

, .

, java .

+1

"Java" ", Java", Scala :

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

Python , .

0
source

AbacusUtil , a generic Java programming library that provides many of the most commonly used methods to make Java programming more fun and more productive:

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

(Declaration: I am the developer of AbacusUtil)

0
source

Source: https://habr.com/ru/post/1751233/


All Articles