3

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?

2
  • You need to have a custom comparator Commented Mar 8, 2016 at 16:11
  • This link may help you programtalk.com/java/sort-list-java Commented Mar 8, 2016 at 16:16

5 Answers 5

6

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());
Sign up to request clarification or add additional context in comments.

2 Comments

See the discussion on @NikolasCharalambidis's answer. This approach suffers from the same issue.
I agree. Using return Long.valueOf(i1.getId()).compareTo(i2.getId()) fix it.
4

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]]

Comments

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.

1 Comment

Succinct and clean! I didn't know about the comparing() method, and I was surprised that it worked even with getId() returning a long value. +1
2

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(...).

2 Comments

id is a long, not an int
The problem is that Comparable's compareTo() method returns an int, but the id is a long. Subtraction won't work. The comparison must be handled using relational operators (e.g. ==, >,<)
1

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 ids yields a long. Instead, you'll have to compare the ids using the (less-concise) relational operations (e.g. >, <, ==. 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);
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.