简体   繁体   English

将动态数据插入2D字符串数组

[英]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. names可能会有所不同,具体取决于我得到的输入。

For example if it is a furniture store, the categories will be Tables , Chairs etc. 例如,如果是家具店,则类别为TablesChairs等。

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"} 并且names包含: {"Wood", "Metal", "4-seater", "6-seater"}

So, I want the childElements array to reflect it like: 所以,我希望childElements数组像这样反映它:

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. 我想坚持使用数组数组,而不要使用listhashmap因为架构依赖hashmap

As @Dude suggested use HashMap, it will help you to organise things easier. 正如@Dude建议使用HashMap,它将帮助您更轻松地组织事物。 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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