【Java】コレクション ~ List編 / 独自のソートをする実装を考える ~

■ カスタムソート

独自のソートをする実装を考える
 * Comparableを実装する必要がある

■ サンプル

Person.java

* Comparableを実装
public class Person implements Comparable<Person> {
   private String companyId;
   private String employeeId;
   private String name;
   
   public Person(String companyId, String employeeId, String name) {
      this.companyId = companyId;
      this.employeeId = employeeId;
      this.name = name;
   }
   
   public String getCompanyId() {
      return this.companyId;
   }
   public void setCompanyId(String companyId) {
      this.companyId = companyId;
   }
   public String getEmployeeId() {
      return this.employeeId;
   }
   public void setEmployeeId(String employeeId) {
      this.employeeId = employeeId;
   }
   public String getName() {
      return this.name;
   }
   public void setName(String name) {
      this.name = name;
   }
   
   @Override
   public int compareTo(Person person) {
      int result = this.companyId.compareTo(person.getCompanyId());
      if (result == 0) {
         result = this.employeeId.compareTo(person.getEmployeeId());
      }
      return result;
   }
}

Main.java

呼び出し側
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

   public static void main(String[] args) {
      List<Person> people = new ArrayList<>();

      people.add(new Person("x03", "e002", "Mike"));
      people.add(new Person("x02", "e002", "Tom"));
      people.add(new Person("x03", "e004", "Smith"));
      people.add(new Person("x01", "e003", "John"));
      people.add(new Person("x02", "e003", "Coco"));
      people.add(new Person("x01", "e001", "Jim"));
      people.add(new Person("x03", "e001", "Kevin"));
      people.add(new Person("x01", "e002", "Kim"));
      people.add(new Person("x02", "e001", "Mary"));
      people.add(new Person("x03", "e003", "Lony"));

      // ソート処理
      Collections.sort(people);

      for (final Person person : people) {
         System.out.println(person.getCompanyId() + " " + person.getEmployeeId() + " " + person.getName());
      }
   }
}

出力結果

x01 e001 Jim
x01 e002 Kim
x01 e003 John
x02 e001 Mary
x02 e002 Tom
x02 e003 Coco
x03 e001 Kevin
x03 e002 Mike
x03 e003 Lony
x03 e004 Smith

関連記事

配列 に関するあれこれ

http://blogs.yahoo.co.jp/dk521123/34123527.html

コレクション ~ List 編~

http://blogs.yahoo.co.jp/dk521123/32156111.html

コレクション ~ List編 / List <=> 配列に変換するには ~

https://blogs.yahoo.co.jp/dk521123/37174513.html