按对象属性对对象的 ArrayList 进行排序 [英] Sorting ArrayList of Objects by Object attribute

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

问题描述

我有一个对象数组列表.这些对象有一个属性或数据类型 - 'String'.我需要按该字符串对 Arraylist 进行排序.如何实现这一目标?

I am having an Arraylist of Objects. Those object have an attribute or datatype - 'String'. I need to sort the Arraylist by that string. How to achieve this?

推荐答案

你需要写一个Comparator 并使用 Collections.sort(List, Comparator 对您的 List 进行排序.

You need to write a Comparator<MyObject> and use Collections.sort(List<T>, Comparator<? super T> to sort your List.

否则,您的 MyObject 也可以 实现 Comparable,定义一个自然排序来比较你的特定属性,然后使用 Collections.sort(List<;T> 代替.

Or else, your MyObject can also implements Comparable<MyObject>, defining a natural ordering that compares on your specific attribute, and then use Collections.sort(List<T> instead.

根据各种条件对 List 进行排序:

On sorting List on various criteria:

关于ComparatorComparable

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

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