繁体   English   中英

基于Java中另一个数组列表中的对象值对数组列表进行排序

[英]Sorting an arraylist based on objects value in another arraylist in Java

我在排序数组列表时遇到问题。 在一个类中,我有两个不同对象的数组列表,我们可以调用对象 Foo 和 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 上,依此类推。

我想要做的是在这些值之后命令 barList 匹配 fooList。 如果值为 5 的 Foo 在索引 13 上,我希望值为 5 的 Bar 在索引 13 上。我最后一次尝试是这样,但没有成功。

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));
    }
});

有没有人知道如何以有效的方式做到这一点?

我不确定您为什么使用barList元素的索引来查看地图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())));

基本上,问题归结为:

给定两个整数列表 A = {a 1 , a 2 ...a n } 和 B = {b 1 , b 2 , ...b m },根据其中元素出现的位置对列表 B 进行排序第一个列表,A。

对于 B 中的两个元素x , y

  • x > y ,如果x在 A 中出现在y之前。
  • x < y ,如果x在 A 中出现在y之后。
  • x = y ,如果x = y

因此, Bar的比较器函数必须比较特定元素在Foo中出现的位置(基于上述)。

注意:这假设(如您所说) Bar中没有Foo没有的元素 Bar中的元素是Foo元素的子集)。

我首先在值上索引barList项目,以便可以快速找到具有适当值的Bar实例。 然后使用它将fooList转换为新的barList 沿线的东西:

Map<Integer, Bar> barMap = barList
    .stream()
    .collect(Collectors
        .toMap(
            Bar::getValue,
            Function.identity());
barList = fooList
    .stream()
    .map(Foo::getValue)
    .map(barMap::get)
    .collect(Collectors.toList());

我认为这在时间上必须是最佳的。 为了内存,你必须在这里建立一个barMap

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM