按字母顺序排列基于其成员项目的“toString”值的Java集合 [英] Alphabetically Sort a Java Collection based upon the 'toString' value of its member items

查看:202
本文介绍了按字母顺序排列基于其成员项目的“toString”值的Java集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为Foo的用户定义的Java类,如:

Assume I have a user defined Java class called Foo such as:

public class Foo 
{

    private String aField;

    @Override
    public String toString()
    {
        return aField;
    }

}

/ p>

and a Collection such as:

List<Foo> aList;

我想要做的是根据每个成员返回的'.toString )'的值。

What I am looking to do is to sort the List alphabetically based upon each member's returned '.toString()' value.

我试过使用Collections.sort()方法,但结果不是我的尝试。
我需要做什么才能做到这一点?

I have tried using the Collections.sort() method, but the result was not what I was attempting. What do I need to do inorder to accomplish this?

推荐答案

使用API​​ sort (列表列表,比较器c)其中指定了一个比较器,实现是你想要的。

Use the API sort(List list, Comparator c)which specifies a comparator, and implement is as you wish.

或者,如果你不需要列出,请使用 SortedSet ,比较器也一样。

Alternatively, if you do not specifically need a List, use a SortedSet, same goes with the comparator.

这篇关于按字母顺序排列基于其成员项目的“toString”值的Java集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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