我有一个 POJO 的数组列表,其中的数据采用以下形式
id time
2 467
3 403
4 602
3 529
5 398
要求是,首先我需要按时间对数据进行排序,然后相同的 ID 应该一个接一个,即
id time
5 398
3 403
3 529
2 467
4 602.
最初为了按时间排序,我使用以下逻辑
Collections.sort(list, new Comparator<Asset>() {
@Override
public int compare(Asset o1, Asset o2) {
if (o1.getTime() > o2.getTime())
return -1;
else if (o1.getTime() < o2.getTime())
return 1;
else
return 0;
}
});
有人可以帮助我在下一阶段通过 ID 进行俱乐部吗?
最佳答案
要根据您提供的示例对数据进行排序,您可能需要对列表进行两次遍历。 (您还如何确定 3 504
应该出现在 5 315
之前还是之后?)
- 按照时间排序。
- 根据每个 ID 的第一个索引对列表进行排序。
这是一些示例代码:
import java.util.*;
class Asset {
public int id;
public int time;
public Asset(int id, int time) {
this.id = id;
this.time = time;
}
public String toString() {
return id + " " + time;
}
}
class Test {
public static void main(String[] args) {
List<Asset> assets = new ArrayList<Asset>();
assets.add(new Asset(2, 467));
assets.add(new Asset(3, 403));
assets.add(new Asset(4, 602));
assets.add(new Asset(3, 529));
assets.add(new Asset(5, 398));
// Sort according to time.
Collections.sort(assets, new Comparator<Asset>() {
@Override
public int compare(Asset o1, Asset o2) {
return new Integer(o1.time).compareTo(o2.time);
}
});
// Remember the original indexes of each asset.
final List<Asset> assetsCopy = new ArrayList<Asset>(assets);
// Sort the collection based on the index of the first asset
// with the same id
Collections.sort(assets, new Comparator<Asset>() {
private int firstIndexOf(int id) {
for (int i = 0; i < assetsCopy.size(); i++)
if (assetsCopy.get(i).id == id)
return i;
return -1;
}
@Override
public int compare(Asset o1, Asset o2) {
return new Integer(firstIndexOf(o1.id))
.compareTo(firstIndexOf(o2.id));
}
});
for (Asset a : assets)
System.out.println(a);
}
}
输出:
5 398
3 403
3 529
2 467
4 602
关于java排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9767103/