tl;dr
To sort by output of toString:
Arrays.sort( persons , Comparator.comparing( Person :: toString ) );
Sort by toString
Other Answers assume you have access to the class and its fields. If so, use those other approaches. But I will take your Question at face value: How to sort by toString.
To answer your Question directly, how to sort by toString output, use Arrays.sort with a Comparator based on a method reference of toString.
Arrays.sort( persons , Comparator.comparing( Person :: toString ) );
As an example, let's define a record class Person. You can define a record locally, if you want, or as a nested or separate class.
record Person( String firstName , String lastName ) { }
With a record, the toString method override is implicitly implemented to access each and every field in the order of their definition. So in our case, toString produces text consisting of the first name followed by the last name.
Sorting is made easier in Java 8+ by way of Comparator.comparing.
Let's generate some example data to exercise this code.
Person[] persons =
List.of(
new Person( "Bob" , "Yates" ) ,
new Person( "Carol" , "Zamora" ) ,
new Person( "Alice" , "Anderson" ) ,
new Person( "Davis" , "Xavier" ) ,
new Person( "Alice" , "Abercrombie" )
)
.toArray( Person[] :: new );
Dump the array to console after sorting. Before Java 25, swap out IO for System.out.
Arrays.stream( persons ).forEach( IO :: println );
When run:
Person[firstName=Alice, lastName=Abercrombie]
Person[firstName=Alice, lastName=Anderson]
Person[firstName=Bob, lastName=Yates]
Person[firstName=Carol, lastName=Zamora]
Person[firstName=Davis, lastName=Xavier]
Notice how all the elements are in order by first name. In the case of a collision between first names, such as Alice here, the last name acts as the tie-breaker given that it is the last part of the String object being compared. Here we see Alice Abercrombie comes before Alice Anderson.
Comparatorand use it for sorting.Comparatorsplit the string and use the first element as the name.