Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- MySQL
- erlang
- Artificial Intelligence
- hbase
- Malaysia
- leadership
- Java
- comic agile
- ubuntu
- Programming
- Python
- Book
- web
- Linux
- QT
- Software Engineering
- Italy
- hadoop
- history
- RFID
- programming_book
- AI
- django
- agile
- France
- Book review
- management
- program
- Kuala Lumpur
- essay
Archives
- Today
- Total
TreeSet, TreeMap comparator 본문
http://blog.naver.com/PostView.nhn?blogId=kimhw9999&logNo=90063726507&viewDate=¤tPage=1&listtype=0
import java.util.*;
public class TestSortSetAndMap
{
public static void main(final String[] args)
{
System.out.println("==========\tset sorting by value");
Set set = new HashSet();
set.add(new String("김삿갓"));
set.add(new String("홍길동"));
set.add(new String("춘향이"));
set.add(new String("이도령"));
set.add(new String("향단이"));
System.out.println("HashSet: " + set);
TreeSet ts = new TreeSet();
ts.addAll(set);
System.out.println("TreeSet: " + ts);
System.out.println("==========\tmap sorting by value");
Map map = new HashMap();
map.put("홍길동", new Integer(1));
map.put("김삿갓", new Integer(2));
map.put("춘향이", new Integer(3));
map.put("이도령", new Integer(4));
map.put("향단이", new Integer(5));
System.out.println("HashMap: " + map);
Map sortedMap = new TreeMap();
sortedMap.putAll(map);
System.out.println("TreeMap: " + sortedMap);
}
}
import java.util.*;
class Score {
private int korea = 0;
private int math = 0;
public Score(int korea, int math) {
this.korea = korea;
this.math = math;
}
public int getSum() {
return this.korea + this.math;
}
public String toString() {
return "국어: " + korea + " 수학: " + math;
}
}
class MyComparator implements Comparator {
public int compare(T o1, T o2) {
Score s1 = (Score)o1;
Score s2 = (Score)o2;
int r = s1.getSum() - s2.getSum();
if ( 0 < r ) {
return 1; // ascending
} else if ( 0 == r ) {
return 0;
} else {
return -1; // descending
}
}
}
public class TestTreeSetComparator {
public static void main(String[] args) {
TreeSet tset =
new TreeSet(new MyComparator());
tset.add(new Score(21, 22));
tset.add(new Score(61, 62));
tset.add(new Score(81, 82));
tset.add(new Score(11, 12));
tset.add(new Score(31, 32));
System.out.println("TreeSet: " + tset);
}
}
import java.util.*;
public class TestTreeMapComparator {
public static void main(final String[] args) {
TreeMap tmap =
new TreeMap(new MyComparator());
tmap.put(new Score(21, 22), "홍길동");
tmap.put(new Score(61, 62), "김삿갓");
tmap.put(new Score(81, 82), "이도령");
tmap.put(new Score(11, 12), "춘향이");
tmap.put(new Score(31, 32), "향단이");
System.out.println("TreeMap sorting: " + tmap);
}
}
Comments