Charlie Harper
Charlie Harper

Reputation: 379

Best way to sort a Set?

i have a class representing cars:

public class Car implements Comparable<Car> {
    String name;
    int value;
    ...
    @Override
    public int compareTo(Car o) {
        return name.compareTo(o.name);
    }
}

and another class representing races:

public class Race {
    cars = new HashSet<Car>();
    ...
    public Collection<Car> sortByName() {
        List<Car> carList = new ArrayList<>(cars);
        Collections.sort(carList);
        return carList;
    }
}

Its my implementation to sorting the Set, i know there is a TreeSet but i dont know how to compare it by TreeSet instead of HashSet, because if i used TreeSet i couldnt find method comprator() in it, can anyone help me if im doing well or if not how to use TreeSet?

Upvotes: 0

Views: 3091

Answers (2)

Clete2
Clete2

Reputation: 417

Use a Comparator instead of Comparable in Car. Comparator is external to the class it compares, whereas Comparable is internal to that class. A more detailed explanation is here: https://stackoverflow.com/a/4108764/1838970

Now, on to your question. Implement this Comparator:

public class CarComparatorByName implements Comparator<Car> {
    public int compare(Car o1, Car o2) {
        return o1.getName().compareTo(o2.getName());
    }
}

Now make a TreeSet using that Comparator:

Set<Car> cars = new TreeSet<Car>(new CarComparatorByName());

That TreeSet will now use the comparator you created.

Alternatively, as noted in the comments below, you could just keep Car as a Comparable and simply throw them into a TreeSet upon creation. That TreeSet will use the natural sort order defined in Car implements Comparable.

Upvotes: 1

nattyddubbs
nattyddubbs

Reputation: 2095

Here's a snippet from the TreeSet javadoc:

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Natural ordering refers to the order that you enforced by making the Car class implement the Comparable interface. Just add your cars to the TreeSet instance and they will be sorted for you.

Upvotes: 2

Related Questions