Sorting an ArrayList of Person with java collections
Solution 1
Collections.sort(List<T>)
method expects the element of the list it is sorting to be comparable. Either the element type T
should implement the Comparable
interface, or you should use the overloaded sort()
method, that takes a generic Comparator
instance.
In the code below, you are satisfying neither of the above conditions. Neither your Person
class implements Comparable
, nor you are passing any Comparator
instance.
ArrayList<Person> nameFromText = new ArrayList<Person>();
fillArrayList(nameFromText, pullFile);
// Sort ArrayList
Collections.sort(nameFromText); // How to sort?
You should create a Comparator
for your Person
class to tell the sort()
method how to sort it (may be on String stored in Person class)
Here's how you implement a generic comparator:
public class PersonNameComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
And then your Collections.sort()
method invocation should be like: -
Collections.sort(nameFromText, new PersonNameComparator());
Solution 2
Alternatively you can implement Comparable interface directly in Person class and override 'compareTo(Object obj) ' method. In this case you would not need to create new class for comparator. And this behaves like inbuilt sorting.
Solution 3
Try this:
List<String> inputString = Arrays.asList("Sijan", "Sudeep", "Parasar", "Raj Kumar");
Collections.sort(inputString);
System.out.println(inputString);
Solution 4
If you using Java 8 then use one liner Lambda Expression
ArrayList<Person> nameFromText = new ArrayList<Person>();
fillArrayList(nameFromText, pullFile);
nameFromText.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));
David Tunnell
https://www.davidtunnell.com Seasoned IT professional with years of experience working on software projects in various capacities (Developer, Tester, Scrum Master, PM) in industries including federal consulting, real estate, industrial construction, healthcare and internet startups. Educated with a Computer Science degree from University of Maryland – University College, an MBA from University of Texas at Austin and most recently completed University of North Carolina at Chapel Hill’s Fullstack Certification. Enjoys being challenged and engaged with projects that require me to work outside my comfort zone and knowledge set, especially while collaborating with a team. Have worked on a variety of technology stacks on both greenfield and existing code bases and have managed/facilitated software teams and implemented Agile/Scrum from the ground up resulting in major successes. Looking to move back into a software development role which is my original passion. The ability to create something that is useful and provides value with my mind, colleagues, and a computer drives me.
Updated on July 09, 2022Comments
-
David Tunnell almost 2 years
Below the code I am using works just fine and outputs the names except that the sort method is not working. I expected "Collections.sort(nameFromText);" to sort the ArrayList in alphabetical order by first name.
What am I doing wrong?
public static void main(String[] args) throws IOException { // Create and populate text file Writer textFile = new FileWriter("names.txt"); String[] nameArray = new String[] { "Tina Tully\n", "Bill Simpson\n", "Dana Smith\n", "Ralph Andrews\n", "Greg Smithers\n", "Lisa Krump\n", "Gill Bitters\n", "Barbara West\n", "Sandra McDonald\n", "Bart Willis\n", "Bucky Zimmerman\n", "Richard Vicks\n", "Velma Tarp\n", "Winslow Tunnell\n", "Andrew Letterman\n", "Betty Trump\n", "Waldo Smith\n", "Kyle Ronno\n", "Vivian West\n", "Wendy Tunnell\n" }; generateText(textFile, nameArray); // Create object of previously created text file Scanner pullFile = new Scanner(new File("names.txt")); // Create 20 Person Objects and add to ArrayList data structure with // name variables assigned to values from text file ArrayList<Person> nameFromText = new ArrayList<Person>(); fillArrayList(nameFromText, pullFile); // Sort ArrayList Collections.sort(nameFromText); // Print ArrayList printNamesFromObjects(nameFromText); } private static void printNamesFromObjects(ArrayList<Person> namesFromText) { for (int i = 0; i < 20; i++) { System.out.println(namesFromText.get(i).name); } } private static void fillArrayList(ArrayList<Person> nameFromText, Scanner pullFile) { while (pullFile.hasNext()) { Person obj = new Person(pullFile.nextLine()); nameFromText.add(obj); } } private static void generateText(Writer textFile, String[] nameArray) throws IOException { for (int i = 0; i < 20; i++) { textFile.write(new String(nameArray[i])); } textFile.close(); }
-
Rohit Jain over 11 years@DavidTunnell Your're welcome.. You can also google - "Difference between Comparator and Comparable` to get more information..
Comparable
is also used for this purpose.. ButComparator
is wider, as you can create multiple sorting logics.. -
Rohit Jain over 11 years+1 Thats a valid point.. But you should prefer
Comparator
overComparable
. That way you can have multiple sorting logics for your class.. -
Satheesh Cheveri over 11 yearsYes, as comparator give you the flexibility when there are more than one sorting candidates.
-
Joao Sousa almost 11 yearsI think you have a typo on your code. Shouldn't it be:
... (Person) o
1; ... Person p2 = (Person) o
2;
?