8

I know that Collections.sort(myArrayList) can sort an arraylist alphabetically when they are strings, but what about when they are something more complex such as a data object containing two or more variables including a String. Is there a way to sort them then?

If there isn't a way with Collections then I can imagine making a for loop or standard sorting algorithm to look at the strings variable of each object and move the object's index in the array.

But I was wondering mainly if I overlooked something about the Collections methods

3
  • The Guava library has great out-of-the-box support for creating composite comparators. Check it out. Commented Nov 14, 2012 at 14:41
  • this might help also stackoverflow.com/questions/2839137/… Commented Nov 14, 2012 at 14:43
  • Reading the JavaDoc will point you in the right direction. Commented Nov 13, 2013 at 21:00

2 Answers 2

28

Use the function taking as second parameter a Comparator.

Il allows you to pass an instance of Comparator to sort according to your needs. Note that the javadoc of Comparator contains guidelines regarding the building of comparators.

You may define the comparator as an anonymous class if it's only locally used. Here's an example where I sort objects regarding to one of their fields which is a String :

Collections.sort(groupResults, new Comparator<ProductSearchResult>() {
    public int compare(ProductSearchResult result1, ProductSearchResult result2) {
        return result1.product.getRsId().compareTo(result2.product.getRsId());
    }
});

Alternatively, you might also make your class implement the Comparable interface but this makes sense only if you can define a natural (obvious) order.

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

2 Comments

Also, regarding implementing Comparable, this makes sense if you always want to order lists of the type in the same way. If you want to have different ordering in different situations, passing a Comparator into Collections.sort() is probably the way to go.
thanks this was the most to the point example of Comparator I've seen
12

I would create an inner class implementing the Comparator interface:

public class Car {
public double horsePower;

class CarHorsePowerComparator implements Comparator<Car> {
    @Override
    public int compare(Car car1, Car car2) {
        return Integer.valueOf(car.horsePower).compareTo(Integer.valueOf(car2.horsePower))          }
    }
}

Now when you want to sort your Car list by horsePower:

List<Car> list = new ArrayList<Car>(myCars); //your Car list
Collections.sort(list, new CarHorsePowerComparator());

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.