オブジェクトを含むarrayListがあり(Dados、Dadosが何であるかは関係ありません)、各オブジェクトにはIDがあります。オブジェクト IDS は、かなりランダムな場合がありますが、常に正しいことが 1 つあります。それらは「低いものから高いものへ」の順序になっています (英語の単語がわからないので、申し訳ありません)。
次のArrayListがあるとしましょう:
[1] [3] [5] [9] [10] [12] [15] [16] [17] [18] [20] [25] [28] [29]
そして、シーケンシャル オブジェクト IDS をグループ化して、後でそれらを TreeMap に配置したいと考えています。上記の例では、TreeMap は次のようになります。
1->[1]
2->[3]
3->[5]
4->[9][10]
5->[12]
6->[15][16][17][18]
7->[20]
8->[25]
9->[28][29]
私が今やっている方法は、配列の最初と最後の要素をスキップすることです: これは私がやっていることです:
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++;
}
}
しかし、配列の最初と最後の位置をスキップすることはできません。この詳細が、このアルゴリズムを修正できない原因です。