I have been dealing with one algorithm to create an automatic structure of an xml file in Java.
The idea is to count the elements in XML file, put them in a list and then count the repeated elements inside,finally create another XML nodes with the amount of the repeated numbers inside that list.
I solved the first problem by using Map <String, Long>
and Collections
to get the repeted elements and number of occurances.
I put them in an Arraylist by converting the number of occurances to int values.
Collection test = counterMap.values();
List <Integer> list = new ArrayList(test);
Iterator listIteration = list.iterator();
ArrayList <Integer> intValues = new ArrayList <>();
while (listIteration.hasNext()) {
int Values = Integer.parseInt(listIteration.next().toString());
intValues.add(Values);
}
Now, I have a list of int values intValues=[1,3,3,4,2,2]
for example.
By using that list, I want to create an XML elements with the numbers of inside this list. I tried for each and for loops to get over it. But I could not.
Element example;
for (int i = 0; i <= list.size(); i++) {
root = doc.createElement("root");
pattern.appendChild(root);
//for (Iterator<Integer> h = intValues.iterator(); h.hasNext();) {
//Integer item = h.next();
for (Integer a : intValues) {
for (int b = 1; b < a; b++) {
example = doc.createElement("example");
root.appendChild(example);
}
}
}
The example output could be:
<root>
<example>
<root>
<root>
<example>
<example>
<example>
<root>
<root>
<example>
<example>
<example>
<root>
<root>
<example>
<example>
<example>
<example>
<root>
(the number of elements as it is in the int arrayList)
Any idea would be nice to move on and Sorry for the mistakes or unclear parts.
##########SOLUTION UPDATE############
I found the solution, I add it here so anybody can have it If they eventually cross with the same problem. Thanks for all the help.
for (Integer a : intValues) {
root= doc.createElement("root");
for (int b = 1; b <= a; b++) {
pattern.appendChild(root);
example= doc.createElement("example");
rule.appendChild(example);
}
}
this part for (int i = 0; i <= list.size(); i++)
is unnecessary. Just removed it and change a bit order in the loops. The output is exactly what I want.