56862

Sort an array of objects alphabetically [duplicate]

Question:

This question already has an answer here:

<ul><li> <a href="/questions/708698/how-can-i-sort-a-list-alphabetically" dir="ltr" rel="nofollow">How can I sort a List alphabetically?</a> <span class="question-originals-answer-count"> 13 answers </span> </li> </ul>

I have an array of objects and each objects has a given name and a surname. These names are written to the object using methods getGivenName and getSurname.

I need to sort the elements in the array in alphabetical order by surname. how can I do this?

Answer1:

Your comparator

class SampleComparator implements Comparator<YourObject> { @Override public int compare(YourObject o1, YourObject o2) { return o1.getSurname().compareTo(o2.getSurname()); } }

Your Sorting

Collections.sort(YourList, new SampleComparator())

if you need ignore case then use like

return o1.getSurname().compareToIgnoreCase(o2.getSurname());

Answer2:

Use List rather than using Array. Your class needs to implements Comparable interface. Please see the code,

<h2>By Implementing Comparable interface</h2> public class Person implements Comparable<Person>{ private String givenName; private String surname; public static void main(String[] args) { Person person1 = new Person("a","b"); Person person2 = new Person("c","d"); Person person3 = new Person("e","f"); List<Person> personList = new ArrayList<Person>(); personList.add(person1); personList.add(person2); personList.add(person3); Collections.sort(personList); System.out.println(personList); } @Override public String toString() { return "WorkSheet [givenName=" + givenName + ", surname=" + surname + "]"; } public Person() { // TODO Auto-generated constructor stub } public Person(String givenName , String surname) { this.givenName = givenName; this.surname = surname; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public int compareTo(Person o) { // TODO Auto-generated method stub return o.getSurname().compareTo(this.getSurname()); } } <h2>By Implementing Comaparator Interface</h2> public class Person implements Comparator<Person>{ private String givenName; private String surname; public static void main(String[] args) { Person person1 = new Person("a","b"); Person person2 = new Person("c","d"); Person person3 = new Person("e","f"); List<Person> personList = new ArrayList<Person>(); personList.add(person1); personList.add(person2); personList.add(person3); Collections.sort(personList , new Person()); System.out.println(personList); } @Override public String toString() { return "WorkSheet [givenName=" + givenName + ", surname=" + surname + "]"; } public Person() { // TODO Auto-generated constructor stub } public Person(String givenName , String surname) { this.givenName = givenName; this.surname = surname; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public int compare(Person o1, Person o2) { // TODO Auto-generated method stub return o2.getSurname().compareTo(o1.getSurname()); } } <hr />

Answer3:

When sorting natural language texts, it's recommended to use a <a href="http://docs.oracle.com/javase/7/docs/api/java/text/Collator.html" rel="nofollow">Collator</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/text/CollationKey.html" rel="nofollow">CollationKeys</a>. The <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo%28java.lang.String%29" rel="nofollow">String.compareTo</a> method mentioned by other answers will compare Strings based on the Unicode value of each character in the strings, which might not be what you want/ expect, depending on your input Strings and locale.

Note that I wrote <a href="http://softsmithy.sourceforge.net/lib/current/docs/api/softsmithy-lib-core/org/softsmithy/lib/text/Localizables.html" rel="nofollow">some utility methods</a> to help sorting natural language texts.

E.g. you coud try something like:

public class PersonLocalizer implements Localizer<Person> { @Override public String getDisplayString(Person person, Locale inLocale) { return person.getSurname(); } } [...] Localizables.sort(new PersonLocalizer (), persons);

Maven:

<dependency> <groupId>org.softsmithy.lib</groupId> <artifactId>softsmithy-lib-core</artifactId> <version>0.3</version> </dependency>

Recommend

  • Convert a string to ZonedDateTime
  • Python Pandas groupby, rank, then assign value based on custom rank
  • dynamodb.transactWriteItems is not a function error on Lambda but not when using VS Code
  • How to get pip to point to newer version of Python
  • force subclasses to include constant in abstract java class
  • Using Internet Explorer filters and ClearType
  • Emberjs custom config variables
  • Issue while running Linux Command using Java?
  • Perl is respecting '
  • How to pivot table for year in SQL?
  • Selenium 2 : finding web element locators programatically
  • How to use mmap to point to STL type?
  • How to Enable Systemd service in openshift/jenkins-1-centos7 docker container?
  • Dynamic reference casting depending on actual object type
  • How to create wsdl from xsd
  • Refresh JSF component after custom javascript Ajax call
  • Multiple canvases (pages) in Fabric.js
  • How to resolve this in PHPUnit where it is asking me to set KERNEL_DIR in my phpunit.xml?
  • Year over Year Stats from a Crossfilter Dataset
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • Cloud Code: Creating a Parse.File from URL
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • Send array to next viewcontroller iOs xcode [duplicate]
  • Bind selectedDates Aggregation for Calendar
  • How to get rgb from transparent pixel in js
  • Codeigniniter insert data through models and controller
  • Call Microservice from another Microservice within Docker
  • Cross compile glibc for arm, got undefined reference to some unwind functions
  • Why does Rails 3 think xE2x80x89 means â x80 x89
  • How do I use TagLib-Sharp to write custom (PRIV) ID3 frames?
  • PHP Permalinks.. how to change?
  • CAS 4 - Not able to retrieve the LDAP groups after successful authentication
  • What does the “id” field in an Android “Google Play Music” broadcast intent correspond to?
  • JavaScript RegExp Replace