1

I am trying to make a catalog for a shop. For that I have a 2D array:

String childElements[][] = new String[][];

I want to add data into this array. The data is another array:

ArrayList<String> names = new ArrayList<String>();

names can vary depending on the input that I get.

For example if it is a furniture store, the categories will be Tables, Chairs etc.

I have my categories stored in another array which is something like:

String groupElements[] = {"Tables", "Chairs"};

And names contains: {"Wood", "Metal", "4-seater", "6-seater"}

So, I want the childElements array to reflect it like:

childElements = ["Chairs"]["Wood", "Metal"]
                ["Tables"]["4-seater"]["6-seater"]

So how do I insert the data to serve my needs?

I would like to stick with an array of arrays and not go for list or a hashmap as the architecture depends on that.

3
  • why not hashmap, you have an key value datatype? Commented May 15, 2015 at 8:07
  • You're trying to convert a one-dimensional datatype (ArrayList<String>) into a two-dimensional datatype. You need to be more clear as to how you wish to format the resulting array. Commented May 15, 2015 at 8:09
  • String childElements = new String[][]; is not a valid syntax Commented May 15, 2015 at 8:14

1 Answer 1

1

As @Dude suggested use HashMap, it will help you to organise things easier. So in your case category will be the key and the value will be the array.

    // create map to store
    Map<String, List<String>> map = new HashMap<String, List<String>>();


    // create list one and store values
    List<String> chairs = new ArrayList<String>();
    chairs.add("Wood");
    chairs.add("Metal");

    // create list two and store values
    List<String> tables = new ArrayList<String>();
    tables.add("4-seater");
    tables.add("6-seater");

    // put values into map
    map.put("Chairs", chairs);
    map.put("Tables", tables);

    // iterate and display values
    System.out.println("Fetching Keys and corresponding [Multiple] Values");
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        String key = entry.getKey();
        List<String> values = entry.getValue();
        System.out.println("Key = " + key);
        System.out.println("Values = " + values);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.