Java Collection How to - Sort a pair of string using collection








Question

We would like to know how to sort a pair of string using collection.

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/*from w  ww .j a  va  2 s .  c  o m*/
class Name implements Comparable<Name> {
  private String firstName;
  private String lastName;

  public Name(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  @Override
  public int compareTo(Name otherName) {
    if (this.firstName.compareTo(otherName.firstName) == 0) {
      return this.lastName.compareTo(otherName.lastName);
    } else {
      return this.firstName.compareTo(otherName.firstName);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Name name = new Name("A", "C");
    Name name1 = new Name("A", "B");
    Name name2 = new Name("C", "F");
    Name name3 = new Name("D", "A");
    Name name4 = new Name("Ca", "D");
    Name name5 = new Name("Cc", "Z");
    Name name6 = new Name("Cc", "W");

    Name nameArray[] = { name, name1, name2, name3, name4, name5, name6 };
    List<Name> names = new ArrayList<Name>(Arrays.asList(nameArray));

    Collections.sort(names);

    for (Name n : names) {
      System.out.println(n.getFirstName() + " " + n.getLastName());
    }
  }
}

The code above generates the following result.