简体   繁体   中英

How to sort custom arraylist by object value integer

I have an ArrayList called ideas:

public ArrayList<Idea> ideas = new ArrayList<Idea>();

In the ideas class i have a private integer value called id.

private long id;
public long getId() {return id;}

How would you sort the ArrayList in ascending and descending values?

You can use Collections.sort(list, comparator) . Using this approach you don't need to edit your Idea class.

Collections.sort(ideas, new Comparator<Ideas>() {
    public int compare(Idea i1, Idea i2) {
        return i1 - i2;
    }
});

To use rever order you can use:

Collections.sort(ideas, (new Comparator<Ideas>() {
    public int compare(Idea i1, Idea i2) {
        return i1 - i2;
    }
}).reverseOrder());

Sorting ArrayList example is given below according to your code

SortIdeaExample.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortIdeaExample {

    public static void main(String[] args) {
        List<Idea> ideaList = new ArrayList<Idea>();
        ideaList.add(new Idea(11l));
        ideaList.add(new Idea(2l));
        ideaList.add(new Idea(13l));
        ideaList.add(new Idea(4l));

        SortIdeaExample sortExample = new SortIdeaExample();
        System.out.println("Before sorting:" + ideaList);
        sortExample.sortList(ideaList);
        System.out.println("Ascending sorted list:" + ideaList);
        sortExample.sortListReverse(ideaList);
        System.out.println("Descending sorted list:" + ideaList);
    }

    private void sortList(List<Idea> list) {
        Collections.sort(list, new Comparator<Idea>() {
            public int compare(Idea ideaVal1, Idea ideaVal2) {
                // avoiding NullPointerException in case name is null
                Long idea1 = new Long(ideaVal1.getId());
                Long idea2 = new Long(ideaVal2.getId());
                return idea1.compareTo(idea2);
            }
        });
    }

    private void sortListReverse(List<Idea> list) {
        Collections.sort(list, new Comparator<Idea>() {
            public int compare(Idea ideaVal1, Idea ideaVal2) {
                // avoiding NullPointerException in case name is null
                Long idea1 = new Long(ideaVal1.getId());
                Long idea2 = new Long(ideaVal2.getId());
                return idea2.compareTo(idea1);
            }
        });
    }
}

Idea.java

public class Idea {
    private long id;

    public Idea(long id) {
        super();
        this.id = id;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Idea [id=" + id + "]";
    }
}

Output:

Before sorting:[Idea [id=11], Idea [id=2], Idea [id=13], Idea [id=4]]
Ascending sorted list:[Idea [id=2], Idea [id=4], Idea [id=11], Idea [id=13]]
Descending sorted list:[Idea [id=13], Idea [id=11], Idea [id=4], Idea [id=2]]

You can do this pretty easily if you are using Java 8 with method pointers. Something like this should do the trick:

ArrayList<Idea> ideas = new ArrayList<Idea>();
ideas.sort(Comparator.comparing(Idea::getId));
ideas.sort(Comparator.comparing(Idea::getId).reversed());

If you are not using Java 8, I would use an anonymous class as mentioned by other answers.

Edit - Works with long . I see other answers having issues with long .

You have to create your own comparator. Implement Comparable class to your Idea class. Then override compareTo() method. It would look like this:

public class Idea implements Comparable<Idea> {

   // Variables, constructor, getters, setters ...

   @Override
   public int compareTo(Idea other) {
      return Long.compare(this.getId(), other.getId());
   }
}

Finally sort with Collections.sort(list);

If you want a reverse result, do this: Collections.sort(list, Collections.reverseOrder());

Also note that the compareTo() method returns int even you want to compare long . That's why you have to use Long.compare(...) .

There are two approaches. Either you can implement a custom Comparator or you can have Idea Implement the Comparable<Idea> interface. But you have to be careful: Since id is of type long , you cannot use subtraction as suggested by the other answers. The compare() and compareTo() methods return an int , but subtracting the id s yields a long . Instead, you'll have to compare the id s using the (less-concise) relational operations (eg > , < , == . Here's how you can accomplish this:

Method 1:

In Java 8: Since Comparator is Functional Interface, you can pass a lambda expression to the ideas.sort() method, as follows:

ideas.sort((i1,i2)->(i1.getId() < i2.getId()) ? -1 : ((i1.getId() == i2.getId()) ? 0 : 1));

In pre-Java 8 : If you are using a version prior to Java 8, you use an annonymous Comparator :

ideas.sort(new Comparator<Idea>(){

    @Override
    public int compare(Idea i1, Idea i2) {
        (i1 < i2) ? -1 : ((i1 == i2) ? 0 : 1)
    }

});

Method 2:

Have the Idea class implement the Comparable<Idea> interface:

public class Idea implements Comparable<Idea>{
    private long id;

    public long getId(){
        return id;
    }

    @Override
    public int compareTo(Idea o) {
        (id < o.id) ? -1 : ((id == o.id) ? 0 : 1);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM