2015/11/08

Java Order List / List Class

Code:
package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class test {

 public static void main(String[] args) {
  sortStringList();
  System.out.println();
  sortClassList();
 }

 private static void sortStringList() {
  String[] array = new String[] { "D", "B", "A", "C" };
  List<String> list = new ArrayList<String>();
  for (String s : array) {
   list.add(s);
   System.out.print(s + " ");
  }
  System.out.println();

  Collections.sort(list);
  for (String s : list) {
   System.out.print(s + " ");
  }
 }

 private static void sortClassList() {
  int[] array = new int[] { 10, 5, 30, 31, 99 };
  List<Size> list = new ArrayList<Size>();
  for (int n : array) {
   int x = 1 * n, y = 2 * n;
   list.add(new Size(x, y));
   System.out.print(String.format("(%d,%d) ", x, y));
  }
  System.out.println();
  Collections.sort(list, new Comparator<Size>() {

   @Override
   public int compare(Size o1, Size o2) {
    return o1.x - o2.x + o1.y - o2.y;
   }

  });

  for (Size s : list) {
   System.out.print(String.format("(%d,%d) ", s.x, s.y));
  }

 }

 private static class Size {
  private int x;
  private int y;

  private Size(int x, int y) {
   this.x = x;
   this.y = y;
  }
 }

}


執行結果:
D B A C 
A B C D 
(10,20) (5,10) (30,60) (31,62) (99,198) 
(5,10) (10,20) (30,60) (31,62) (99,198)