It was not clear, but in his example apparently there is always a Pattern, one type and a value. So why not create an object with these attributes?
public class Element {
private String pattern, type, value;
public Element(String pattern, String type, String value) {
this.pattern = pattern;
this.type = type;
this.value = value;
}
// get, set
}
And then, instead of creating a monstrous structure of HashMap<String, HashMap<String, HashMap<...
you would have a simple map of Element
. For example:
// pattern, type, value
Element input = new Element("[\\+]\\d{2}[\\(]\\d{2}[\\)]\\d{4}[\\-]\\d{4}", "tel", "+91 98111222333");
Element button = new Element("", "button", "validate");
HashMap<String, Element> map = new HashMap(){{
put("input1", input);
put("button1", button);
}};
To go through that map, can use the interface Entry
:
for(Entry<String, Element> each : map.entrySet()){
// No caso, a 'key' é a String com o nome do elemento.
System.out.println("Nome do elemento: " + each.getKey());
// E o 'value' é o nosso objeto 'Element'.
Element current = each.getValue();
System.out.println("Pattern: " + current.getPattern());
System.out.println("Type: " + current.getType());
System.out.println("Value: " + current.getValue());
}
ouput:
Name of the element: input1
Pattern: [+]\d{2}[(]\d{2}[)]\d{4}[-]\d{4}
Type: tel
Value: +91 98111222333
Name of the element: button1
Pattern:
Type: button
Value: validate
Answer before the question is edited:
You can use the method toString
of Arrays
:
System.out.println(Arrays.toString(hm.get("joao")));
output:
[10, 2015, 10101]
Or you can go through the array normally:
for(String each : hm.get("joao"))
System.out.println(each);
output:
10
2015
10101
I tested it in Eclipse and it continues with the same error :(
– Paulo Costa
updated with current code
– Paulo Costa
In PHP it would be simple to create that structure, now in Java I’m breaking Kuka
– Paulo Costa
System.out.println(hm);
– Paulo Costa
Ah, now that I see you’ve edited the question and changed the structure.
– Renan Gomes
Yeah, it’s hard to create that simple structure :(
– Paulo Costa
I was editing my answer but you edited it again
– Renan Gomes
I just made it clear :)
– Paulo Costa
I edited again.
– Renan Gomes
I deleted the question there. Very good your answer.
– Paulo Costa
What if my page has 100 inputs? I will need to instantiate 100x?
– Paulo Costa
But
input1
is only the key to finding the object of map, can be any name there. If your page has 100 inputs, you can instantiate a single and loop to add it 100 times in the map. Do you really need 100 elements within the collection? Wouldn’t it be more feasible to group elements with identical properties? Anyway, that’s another question.– Renan Gomes
True. You’re right. Thank you
– Paulo Costa