按字母顺序排序复杂对象的数组列表 [英] sort arraylist of complex objects alphabetically

查看:252
本文介绍了按字母顺序排序复杂对象的数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Collections.sort(myArrayList)可以在字符串时按字母顺序对数组列表排序,但是当它们是更复杂的数据对象时,两个或多个变量,包括 String 。是否有办法对它们进行排序?

I know that Collections.sort(myArrayList) can sort an arraylist alphabetically when they are strings, but what about when they are something more complex such as a data object containing two or more variables including a String. Is there a way to sort them then?

如果没有办法用 Collections 使用for循环或标准排序算法来查看每个对象的字符串变量并在数组中移动对象的索引。

If there isn't a way with Collections then I can imagine making a for loop or standard sorting algorithm to look at the strings variable of each object and move the object's index in the array.

但我想知道主要是否忽略了集合方法

But I was wondering mainly if I overlooked something about the Collections methods

推荐答案

使用函数作为第二个参数a Comparator

传递Comparator的实例以根据您的需要进行排序。请注意, Comparator 的javadoc包含有关构建

Il allows you to pass an instance of Comparator to sort according to your needs. Note that the javadoc of Comparator contains guidelines regarding the building of comparators.

如果比较器仅在本地使用,您可以将其定义为匿名类。下面是一个示例,其中我对对象关于其中一个字段排序是一个字符串:

You may define the comparator as an anonymous class if it's only locally used. Here's an example where I sort objects regarding to one of their fields which is a String :

Collections.sort(groupResults, new Comparator<ProductSearchResult>() {
    public int compare(ProductSearchResult result1, ProductSearchResult result2) {
        return result1.product.getRsId().compareTo(result2.product.getRsId());
    }
});

或者,您也可以让类实现可比较的界面,但这只有在您可以定义自然(明显)顺序时才有意义。

Alternatively, you might also make your class implement the Comparable interface but this makes sense only if you can define a natural (obvious) order.

这篇关于按字母顺序排序复杂对象的数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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