根据Java中另一个arraylist中的对象值对arraylist进行排序 [英] Sorting an arraylist based on objects value in another arraylist in Java

查看:660
本文介绍了根据Java中另一个arraylist中的对象值对arraylist进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对数组列表进行排序时遇到问题. 在一个类中,我有两个不同对象的数组列表,我们可以将对象称为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个Foos,但是值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());
    }
});

可以通过单线简化此操作

This can be simplified with a one-liner

Collections.sort(barList, Comparator.comparingInt(bar -> positions.get(bar.getId())));


基本上,问题可以归结为:


Basically, the problem boils down to this:

给出两个整数列表A = {a 1 ,a 2 ... a n },B = {b 1 ,b 2 ,... b m },根据元素在第一个列表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< y ,如果 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中另一个arraylist中的对象值对arraylist进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆