所以,
我遇到了一种情况,我使用整数列表从不同来源获取一些数据。结果,我得到两个列表,它们都具有相同的 POJO 类型作为内容,并且包含输入列表中的所有元素,但顺序未知。
我需要的是按照与我的第一个列表相同的顺序对这些 POJO 进行排序(这个 Integer 是 POJO 中具有 getter/setter 的字段),因此我得到一个 POJO 的列表,其顺序与我的 Integer 完全相同列表。
所以,我想到的步骤是:
- 将两个 POJO 列表合并为一个,这样我至少有 2 个大小相同的列表(Integer 和 POJO),我知道它们包含匹配的元素。
- 对生成的 POJO 列表进行排序以匹配 Integer 列表。
但是,对于第 2 步,我需要找到好的(即高效且简洁)方法来完成它...我正在考虑创建一个类似这样的比较器:
public class POJOComparable implements Comparator<MyPOJO>{
private List<Integer> values;
public POJOComparable(List<Integer> values) {
this.values = values;
}
@Override
public int compare(MyPOJO o1P, MyPOJO o2P) {
int o1 = values.indexOf(o1P.getId());
int o2 = values.indexOf(o2P.getId());
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
现在,这是进行此类排序的好方法还是有更好或更有效的方法?列表将包含大约 20 个项目,但这种排序会经常执行,因此我正在寻找有效的方法来执行此操作。
最佳答案
存储您的 List<MyPojo>
的值在 TreeMap<Integer, MyPojo>
并让这个集合为您进行排序。实现此目的的一个简单方法是:
TreeMap<Integer, MyPojo> aSortedMap = new TreeMap<Integer, MyPojo>();
for(MyPojo pojo : aListOfMyPojo) {
aSortedMap.put(values.indexOf(pojo.getId()), pojo);
}
请注意,此方法假设每个 pojo.getId()
List<Integer> values
内有一个唯一值.
基于@BoristheSpider 评论,而不是 List<Integer> values
并求 pojo.getId()
的每个值使用List#indexOf
,最好使用 Map<Integer, Integer>
您存储 pojo.getId()
值的位置和所需的Integer
加速搜索过程的值(value)。因此,最终的算法应如下所示:
//replace the List<Integer> by a Map<Integer>
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
//store the pojo.getId() value with its associated int value
values.put(pojo.getId(), ...);
//...
TreeMap<Integer, MyPojo> aSortedMap = new TreeMap<Integer, MyPojo>();
for(MyPojo pojo : aListOfMyPojo) {
aSortedMap.put(values.get(pojo.getId()), pojo);
}
关于java - 根据整数列表对 POJO 集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18060593/