用多个条件对ArrayList进行排序

编程入门 行业动态 更新时间:2024-10-23 08:32:39
本文介绍了用多个条件对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()pareTo(o2.getCity()); }else{ return o1.getAge()pareTo(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进行排序

本文发布于:2023-10-15 02:48:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   条件   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!