Reputation: 7980
I've an arrayList with objects (Dados, it doesn't matter what Dados is) and each object has an ID. The object IDS, they can be pretty random but one thing is always true, they are in "lower to higher" order (don't know the word in english, sorry).
Let's say I've the following ArrayList:
[1] [3] [5] [9] [10] [12] [15] [16] [17] [18] [20] [25] [28] [29]
And I want to group the sequencial object IDS together to later on put them on a TreeMap. With the example above, the TreeMap will be:
1->[1]
2->[3]
3->[5]
4->[9][10]
5->[12]
6->[15][16][17][18]
7->[20]
8->[25]
9->[28][29]
The way I'm doing it now is skipping the first and last element of the Array: This is what I'm doing:
for(int i = 1; i<arrayWithData.size()-1; i++)//arrayWithData is the initial array with all the objects in it that I need to process
{
ArrayList<Dados> final_sequence = new ArrayList<>(); //the array with the list of Dados
int current = arrayWithData.get(i).getId();
int previous = arrayWithData.get(i-1).getId();
int next = arrayWithData.get(i+1).getId();
/*
* Group Dados, sequencial Dados go together
*/
if(current == next-1)
{
initial_sequence.add(arrayWithData.get(i));
}
else if(current == previous+1)
{
final_sequence.addAll(initial_sequence);
initial_sequence.clear();
final_sequence.add(arrayWithData.get(i));
tmap.put(tmap_key, final_sequence); //tmap is the TreeMap
tmap_key++;
}
else //if it is not a sequencial value
{
final_sequence.add(arrayWithData.get(i));
tmap.put(tmap_key, final_sequence);
tmap_key++;
}
}
But I can not skip the first and last position in the Array, and this detail is what is making me not able to fix this algorithm.
Upvotes: 0
Views: 104
Reputation: 16364
Wouldn't it work just to iterate through the list and add to the treemap when there is a gap in the ids?
List<Dados> next = new ArrayList<Dados>();
for(Dados d : arrayWithData) {
if(!next.isEmpty() && next.get(next.size() - 1).getId() != d.getId() - 1) {
tmap.put(tmap_key++, next);
next = new ArrayList<Dados>();
}
next.add(d);
}
if(!next.isEmpty()) {
tmap.put(tmap_key++, next);
}
Upvotes: 3