0

I'm trying to do something like this:

public Object categories = new Object(
    "Entertainment": new Object(
        "Movie": null),
    "Exercise": new Object(
        "Upper Body": null,
        "Lower Body": new Object(
            "Squats": null
        ),
        "Dance": null)
);

@Paŭlo Ebermann's answer at How to directly initialize a HashMap (in a literal way)? seemed close but it would be quite ugly and cumbersome to use that technique if the nesting went beyond 2 or 3 levels.

I need to be able to put this object in a for-each loop to dynamically create buttons for each node. I come from a javascript background where this sort of thing is trivial. Is there something similar in Java?

Community
  • 1
  • 1
Jpaji Rajnish
  • 1,491
  • 4
  • 17
  • 35
  • Java is OO language, so you should implement classes and instantiate objects whenever you need, for example: Category, Entertainment, Exercise etc. One class can have other classes as its members, this way you can "nest" as much as you want without complicating anything. – Nir Alfasi Jun 29 '15 at 01:46
  • The code like this does not strike me as especially readable or type-safe, when written in Java. Most people would advice you to create a number of classes (possibly nested ones) and use static factory methods to create them. If you want that syntax anyway, consider learning Groovy. It can do this (via typesafe named parameters) and much more. It has decent Android support (one of developers of Android Gradle plugin was a major Groovy contributor). – user1643723 Jun 29 '15 at 01:47
  • @user1643723 Hey I'm not trying to work against the language and force my habits on it. I admit I'm a java newb and so I don't know what would be an efficient way to solve this problem. If Android used javascript I'd be set! :) – Jpaji Rajnish Jun 29 '15 at 01:51
  • Alternatively, consider moving whole logic to more domain-specific language. For instance, you may use json or xml to define the structure as you want, and parse that to generate your buttons in code. This is essentially what Android system does each time it inflates layout from xml. – user1643723 Jun 29 '15 at 01:52
  • @user1643723 I didn't think of that! I will look into it, good idea!! – Jpaji Rajnish Jun 29 '15 at 01:55
  • 1
    You should look at Gson when you're at it - it converts to/from JSON-to-Java-Objects https://code.google.com/p/google-gson/ – Nilzor Jun 29 '15 at 07:40

0 Answers0