-1

I know that we can use TreeSet to sort Strings and numbers in an natural order. What if there is a Set of objects?

For example:

I have a Person class
{
     private String firstName;
     private String lastName;
     private int age;

}

Set person = new TreeSet();

I want person sorted by firstName when I initialize person.

3

1 Answer 1

2

Both Comparable and Comparator work for you, but I suggest Comparator because it doesn't require you modify Person class, you only need the write an implementation class based on the sorting attribute, therefore Comparator is much more flexiable:

import java.util.Comparator;
public class FirstNameComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        String name1 = o1.getFirstName();
        String name2 = o2.getFirstName();
        return name1.compareTo(name2);
    }

}

//instantiate TreeSet instance with FirstNameComparator
Set<Person> ts = new TreeSet<>(new FirstNameComparator());
Sign up to request clarification or add additional context in comments.

4 Comments

Collections.sort takes in a List, so that won't work with a Set. But, since OP is using TreeSet, there's a constructor that accepts a Comparator, which would work here.
I suggest Comparator because it doesn't require you modify Person class. There's nothing wrong with modifying a class that should have natural ordering. A much stronger argument is that a class like Person probably doesn't have a single natural order.
@MickMnemonic thanks Mick. My fault, I thought it took iterable.
@shmosel thanks for your comment and you're right. What I thought was we might not control over the class Person.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.