0

I want to create multiple key/value arrays in Java that will sit in a master array. I then want to be able to loop through the master array and grab the key/value of each array.

I want the array to be in a similar style to this XML:

<snippets>
  <snippet1>
    <name>Name</name>
    <desc>Desc</desc>
  </snippet1>
  <snippet2>
    <name>Name</name>
    <desc>Desc</desc>
  </snippet2>
</snippets>

or is there a way I can do this without using arrays?

4 Answers 4

1

Probably a good case for using classes :) This should get you started (and is pretty unsophisticated):

class Snippets {
   private List<Snippet> snippets;
   List<Snippet> getSnippets() { ... };
   ...
}
class Snippet {
   private String name;
   private String desc;
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Google Collection's Multimap data structure. More specifically to get duplicate key/value pairs you can use ListMultiMap.

Also take a look at this similar question.

If you do not need duplicate key/value pairs, then just use standard java HashMap implementation of the Map interface.

Comments

0

If you REALLY want to use arrays, here's an example:

String[][] snippets = new String[][] {
  new String[] { "Name" , "Desc" },
  new String[] { "Name2" , "Desc2" },
};

for(String[] pair: snippets) {
  String key = pair[0];
  String val = pair[1];
}

Comments

0

I would use (Hash)Maps and (Array)Lists.

You can store everything in a Object like this:

List<Map<String,String>> yourList = new ArrayList<Map<String,String>>();

Map<String,String> map1 = new HashMap<String,String>();
map1.put("key1", "value1");
map1.put("key2", "value2");
yourList.add(map1);

This is how you loop through it:

for (Map<String,String> map: yourList) 
  for (Entry<String, String> entry: map.entrySet())
    System.out.println(entry.getKey()+": "+entry.getValue());

6 Comments

HashMap will not allow duplicate key value pairs as the OP asked for.
I thought "Name" and "Desc" should be placeholders. You'r right, I can't exactly rebuild his XML with Maps...
I am not exactly sure myself but just going by the data given in the question. I have added the assumption in my answer.
name and desc are meant to be keys, like <name>ExampleName</name>. Sorry for not making it clear enough :(
Sounds like you just need a simple HashMap. No need to create a list of Maps.
|

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.