David
David

Reputation: 2721

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

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?

Upvotes: 2

Views: 15167

Answers (4)

Waldheinz
Waldheinz

Reputation: 10487

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

    }

}

Upvotes: 3

tfk
tfk

Reputation: 422

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.

Upvotes: 9

CSan
CSan

Reputation: 954

Simply write a class that implements Comparator-Interface.

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

For more informations read this tutorial

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240996

You can use Custom Comparator

See Also

Upvotes: 1

Related Questions