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?
CodePudding user response:
Your problem is that you are converting your Collection/ArrayList to an array and then sort that Array.
Sorting that Array will have no effect on the original ArrayList.
If you want to sort your List you first need to declare it as a List, because Collections themself have no predefined order and therefor no sort method for them exists, and then in a second step use the corresponding method to sort that list:
public static void main(final String[] args) {
final List<Person> people = new ArrayList<>();
people.add(new Person("aaa", "hhh"));
people.add(new Person("aaa", "aaa"));
people.add(new Person("aaa", "uuu"));
Collections.sort(people, Comparator.comparing(Person::toString));
System.out.println(people);
}
Will output
[aaaaaa, aaahhh, aaauuu]