基于Java中另一个数组列表中的对象值对数组列表进行排序 [英] Sorting an arraylist based on objects value in another arraylist in Java
问题描述
我在排序数组列表时遇到问题.在一个类中,我有两个不同对象的数组列表,我们可以调用对象 Foo 和 Bar.
I have an issue with sorting an Array List. In a class i have two Array Lists of different objects, we can call the objects Foo and Bar.
public class Foo() {
int value;
//Some other fields, and setters and getters.
}
public class Bar() {
int id;
//Same here...
}
所以列表 fooList 可以完全打乱.假设我有 16 个 Foo,但值为 5 的 Foo 可以在索引 13 上,依此类推.
So the list fooList can be totally scrambeled. Say that i have 16 Foos, but Foo with value 5 can be on index 13 and so on.
我想要做的是在这些值之后订购 barList 以匹配 fooList.如果值为 5 的 Foo 在索引 13 上,我希望值为 5 的 Bar 在索引 13 上.我最后一次尝试是这样,但没有成功.
What i'm trying to do is to order barList to match fooList after these values. If Foo with value 5 is on index 13, i want Bar with value 5 to be on index 13. My last attempt was this, but no success.
HashMap<Integer, Integer> positions = new HashMap<>();
for(int i=0;i<fooList.size();i++){
positions.put(foo.get(i).getValue, i);
}
Collections.sort(barList, new Comparator<Bar>(){
public int compare(Bar obj1, Bar obj2){
return positions.get(barList.indexOf(obj1)) -
positions.get(barList.indexOf(obj2));
}
});
有人知道如何以有效的方式做到这一点吗?
Does anybody have a clue how to do this in an efficient way?
推荐答案
我不知道你为什么使用 barList
中元素的索引来查看地图 positions代码>.
I'm not sure why you are using the index of an element in barList
to look into the map positions
.
这应该对你有帮助
Collections.sort(barList, new Comparator<Bar>() {
@Override
public int compare(Bar o1, Bar o2) {
return positions.get(o1.getId()) - positions.get(o2.getId());
}
});
这可以用单行来简化
Collections.sort(barList, Comparator.comparingInt(bar -> positions.get(bar.getId())));
<小时>
基本上,问题归结为:
Basically, the problem boils down to this:
给定两个整数列表 A = {a1, a2...an} 和 B = {b1, b2, ...bm},根据元素在第一个列表A中出现的位置对列表B进行排序.
Given two lists of integers A = {a1, a2...an} and B = {b1, b2, ...bm}, sort the list B based on the position of occurrence of the element in the first list, A.
对于 B 中的两个元素 x, y
For two elements x, y in B
- x > y,如果 x 在 A 中出现在 y 之前.
- x
,如果 x 出现在 A 中的 y 之后. - x = y,如果 x = y
- x > y, if x appears before y in A.
- x < y, if x appears after y in A.
- x = y, if x = y
因此,Bar
的比较器函数必须比较特定元素在 Foo
中出现的位置(基于上述).
So, the comparator function for Bar
has to compare the position at which a particular element has appeared in Foo
(based on the above).
注意: 这假设(如您所说)Bar
中没有 没有元素,而 Foo 中没有代码>.(
Bar
中的元素是 Foo
中元素的子集).
NOTE: This assumes (as you have said) that there is no element in Bar
that is not there in Foo
. (The elements in Bar
are a subset of the elements in Foo
).
这篇关于基于Java中另一个数组列表中的对象值对数组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!