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

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

问题描述

说我有一个数组列表 MyArrayList< MYObject>

myObject类如下:

myObject class looks like :

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

我的虚拟数据如下:

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

如您所见,以上数据以两种方式排序-首先按城市排序,然后按 age 排序,所以这就是我想做的事情,我想对按顺序排列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天全站免登陆