对具有多个条件的 ArrayList 进行排序 [英] sort an ArrayList with multiple conditions

查看:44
本文介绍了对具有多个条件的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组列表 MyArrayList

say i have an array list MyArrayList<MYObject>

myObject 类看起来像:

myObject class looks like :

public class myObject
{
      String name;
      Int age;
      String : city;
}

我的虚拟数据如下所示:

and my dummy data looks like this :

name : martin ,  age : 20 , city : NY
name : felix ,  age : 19 , city : LA
name : brian ,  age : 21 , city : NY
name : brian ,  age : 19 , city : NY

现在我想按此顺序对 myArraylist(其中包含上述数据)进行排序 -

now i wanna sort myArraylist (which have the above data in it) in this order -

name : felix , lastname : 19 , city : LA
name : brian , lastname : 21 , city : NY
name : martin , lastname : 20 , city : NY
name : brian , lastname : 19 , city : NY

如您所见,上述数据以两种方式排序 - 首先按城市,然后按年龄,所以这就是我想要做的,我想对一个arrayList 按顺序然后我想通过保持第一个顺序按另一个顺序排序

as you can see that the above data is sorted in two ways - firstly by cities then again by age so this is what i wanna do , i wanna sort an arrayList by an order then again i wanna sort in another order by keeping the first order

有人知道我该怎么做吗??请告诉我然后

anyone knows how can i do it ?? please let me know then

如果我的问题不够清楚,请告诉我我会解决它

if my question is not clear enough then let me know i'll fix it

推荐答案

您可以创建一个比较器,先按城市比较,然后按年龄比较.像这样:

You can create a Comparator to first compare by city, then by age. Something like this:

Comparator<MyObject> comparator = new Comparator<MyObject>(){
    @Override
    public int compare(final MyObject o1, final MyObject o2){
       if(!o1.getCity().equals(o2.getCity())){
          return o1.getCity().compareTo(o2.getCity());
       }else{
          return o1.getAge().compareTo(o2.getAge());
        }
    }
  };

Collections.sort(myArrayList,comparator);

我使用了 Integer 类的compareTo"方法,您不能在 int 原始类型上调用该方法.如果你使用 int 作为年龄,你可以写出一个 if 语句来进行比较.

I used the "compareTo" method of the Integer class, which you can't call on an int primitive type. If you use int for the age, you could just write out an if statement for the comparison.

这篇关于对具有多个条件的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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