开发者

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

开发者 https://www.devze.com 2023-03-13 14:32 出处:网络
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 v

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?


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

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.


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;
            }
        });

    }

}


You can use Custom Comparator

See Also

  • sorting-a-list-of-points-with-java


Simply write a class that implements Comparator-Interface.

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

For more informations read this tutorial

0

精彩评论

暂无评论...
验证码 换一张
取 消