简体   繁体   中英

Traverse a Map in Java Pythonically?

I'm not really sure if "traversal" is the right word, but in Python, I can do this:

restaurantDict['menus'][menuIdx]['sections'][sectionIdx]['option_groups'][sectionOptionGroupIdx]['options'] = sectionOptionObjects

Is it possible to "traverse" a Map in Java in this style? Or is Python just wild and crazy like that?

Yes, it's possible in Java. You just need to chain .get calls for all but the last key, and then call .put:

// Equivalent Python code: foo["a"]["b"]["c"] = "bar";
HashMap<String, HashMap<String, HashMap<String, String>>> foo = new HashMap<String, HashMap<String, HashMap<String, String>>>();
foo.get("a").get("b").put("c", "bar");

This is a fairly unpleasant thing to do in Java, because this isn't very idiomatic Java code.

Whereas Python encourages defining objects and their relations on the fly, good Java code lays out what kinds of objects you're dealing with in advance by defining appropriate classes. Stacking dicts might be OK in Python, but it makes for horrible Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM