So I'm trying to lexicographically sort this collection but with no success. The same unsorted collection is in the input and the output of the sort method.
class Person {
private String privateName;
private String lastName;
public Person(String privateName, String lastName) {
this.privateName = privateName;
this.lastName = lastName;
}
public String toString() {
return privateName + " " + lastName;
}
}
class Main {
public static void main(String[] args) {
Collection<Person> people = new ArrayList<>();
people.add(new Person("aaa", "hhh"));
people.add(new Person("aaa", "aaa"));
people.add(new Person("aaa", "uuu"));
Arrays.sort(people.toArray(), Comparator.comparing(Object::toString));
}
}
The order of the elements in the output collection: "aaa hhh" -> "aaa aaa" -> "aaa uuu"
While I want it to be: "aaa aaa" -> "aaa hhh" -> "aaa uuu"
Can somebody tell me why?
Collection<Person> peopletoList<Person> peoplewhich will let you usepeople.sort(Comparator.comparing(Object::toString)). Currently you are sorting array created viapeople.toArray(), notpeoplelist itself.