2

Here's an example of what I'm trying to do:

public class Item {
    private int worth;

    public Item(int worth) {
        this.worth = worth;
    }

    public int getWorth() { return worth; }
}

public class Foo {
    public Foo() {
       List<Item> items = new ArrayList<>();
       items.add(new Item(50));
       items.add(new Item(892));
       items.add(new Item(12));
       // Sort?
    }
}

So that the items will be ordered like so

List{
    Item(892)
    Item(50)
    Item(12)
}

Not exactly sure where I should go from here, the Arrays.sort() method would be amazing if I could figure out how to sort it by an integer inside of the class.

2 Answers 2

4

You can create your own class that implements Comparator<Item>. The only method you need to define is the compare method, which compares 2 Items. It returns a negative number, 0, or a positive number depending on whether the first item is less than, equal to, or greater than the second item, respectively.

In this case, with a descending sort, when the first item is less than the second item return a positive number, and when the first item is greater than the second item, return a negative number. This will create a descending order.

Arrays.sort is for arrays, but Collections.sort does the same thing for collections (and it uses Arrays.sort internally anyway). Both methods only need to know from the caller how to compare the items, so that it can sort them correctly.

Pass an instance of your Comparator to a call to Collections.sort, and it will sort your list for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. the links made this really simple.
0

Change your Foo constructor as follows

public Foo() {
   List<Item> items = new ArrayList<>();
   items.add(new Item(50));
   items.add(new Item(892));
   items.add(new Item(12));
   Collections.sort(items, new Comparator<Item>() {

        public int compare(Item o1, Item o2) {

            return    Integer.valueOf(o1.getWorth()).compareTo(Integer.valueOf(o2.getWorth()));
    }
    });
}

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.