简体   繁体   中英

Insert dynamic data into 2D array of strings

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.

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);
    }

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