달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

http://suite.tistory.com  fs 2011.2                                      

자바에서 리스트 객체의 멤버 값에 따라 정렬시

Collections.sort() 를 사용해보는데 한개 변수로 올림/내림 차순 정렬외
한개의 변수의 값이 같을때 2차로 정렬을 할려고하니 검색해도 잘안나와 적어봄~~

ex) 포인트가 높고 같을때는 최신날짜 순으로 할때

1. 객체 class

public class box {
 int point;
 int date;
 String title;
}

2.비교함수용 implements Comparator 클래스

import java.util.Comparator;

class comparator implements Comparator<box> {

 public int compare(box box1, box box2) {

  int ret = 0;
  if (box1.point < box2.point) {
   ret = 1;
  }
  if (box1.point == box2.point) {
   if (box1.date < box2.date) {
    ret = 1;
   }
  }
  return ret;
 }
//문자열이면 compareTo()를 활용하면 될것같음
}


3. main 클래스

import java.util.ArrayList;
import java.util.Collections;

public class test1 {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  ArrayList<box> al = new ArrayList();

  box b1 = new box();
  b1.point = 100;
  b1.date = 201012;
  b1.title = "제목1";
  al.add(b1);
  box b2 = new box();
  b2.point = 200;
  b2.date = 201101;
  b2.title = "제목2";
  al.add(b2);

  box b3 = new box();
  b3.point = 200;
  b3.date = 201102;
  b3.title = "제목3";
  al.add(b3);

  System.out.println("정렬전");
  for (int i = 0; i < al.size(); i++) {
   System.out.print(al.get(i).title);
   System.out.print("," + al.get(i).point);
   System.out.println("," + al.get(i).date);
  }

  Collections.sort(al, new comparator());

  System.out.println("\n정렬후\n");
  for (int i = 0; i < al.size(); i++) {
   System.out.print(al.get(i).title);
   System.out.print("," + al.get(i).point);
   System.out.println("," + al.get(i).date);
  }
 }
}


4. 실행결과
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
정렬전
제목1,100,201012
제목2,200,201101
제목3,200,201102

정렬후

제목3,200,201102
제목2,200,201101
제목1,100,201012
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

:
Posted by mastar