java 如何按元素的一个字段的值对java中的链表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6369757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:37:16  来源:igfitidea点击:

how to sort the linkedlist in java by value of one filed of the element?

javalinked-list

提问by David

I use a linkedlist in my java program, and the element is a custom type which has three fields, one of them is of Integer type. My problem is: how to sort the linkedlist according the value of the Integer filed?

我在我的java程序中使用了一个链表,元素是一个自定义类型,它有三个字段,其中一个是整数类型。我的问题是:如何根据整数字段的值对链表进行排序?

回答by tfk

You can use the Collections.sort method with a custom Comparator.

您可以将 Collections.sort 方法与自定义比较器一起使用。

Collections.sort(your_list, new Comparator<YoureValueType>(){
   @Override
   public int compare(YoureValueType o1, YoureValueType o2){
        if(o1.getMagicInt() < o2.getMagicInt()){
           return -1; 
        }
        if(o1.getMagicInt() > o2.getMagicInt()){
           return 1; 
        }
        return 0;
   }
}); 

Edit: I just saw Alexandr comment about very large and small values on waldheinz answer. I updated my code to reflect his argument.

编辑:我刚刚看到 Alexandr 评论关于 waldheinz 答案的非常大和非常小的值。我更新了我的代码以反映他的论点。

回答by Waldheinz

You can use a Comparator which knows how to sort your Objects like this:

您可以使用一个比较器,它知道如何对您的对象进行排序,如下所示:

public class Foo {

    public String ignoreMe;
    public int sortOnMe;
    public Object ignoreMeToo;

    public static void main() {
        final List<Foo> unsorted = new LinkedList<Foo>();

        // add elements...

        Collections.sort(unsorted, new Comparator<Foo>() {

            @Override
            public int compare(Foo o1, Foo o2) {
                return o1.sortOnMe < o2.sortOnMe ? -1 : o1.sortOnMe == o2.sortOnMe ? 0 : 1;
            }
        });

    }

}

回答by Jigar Joshi

You can use Custom Comparator

您可以使用自定义 Comparator

See Also

也可以看看

回答by Lodger

Simply write a class that implements Comparator-Interface.

只需编写一个实现 Comparator-Interface 的类。

Than use Collections.sort(list, comparator) to sort your List.

比使用 Collections.sort(list,comparator) 对您的列表进行排序。

For more informations read this tutorial

有关更多信息,请阅读本教程