2010年6月3日 星期四

Collection of Sorting

1. 目前 set 可用的為 Tree set 且 Hash 也是 Tree Hash 才可 sort

a. 使用 SortedSet 與 TreeSet
{{{
import java.util.*;


public class TestSortSet {
public static void main(String[] args) {
//Create a hash set
SortedSet set = new TreeSet();

// Add strings to the set
set.add("London");
set.add("Paris");
set.add("New Yourk");


System.out.println(set);

// Obtain an iterator for the hash set
Iterator iterator = set.iterator();

// Display the elements in the hash set
while (iterator.hasNext()) {
System.out.print(iterator.next() + "");
}
}
}

OutPut:
[London, New Yourk, Paris]
London New Yourk Paris


}}}


b. 使用 SortedMap 與 TreeHash
{{{
import java.util.*;


public class SortedMapTest {
public static void main(String[] args) {
//Create a hash set
SortedMap m = new TreeMap();

// Add strings to the set
m.put("/home/Andy", "value1");
m.put("/home/", "value2");
m.put("/home/Andy/Desktop", "value3");



// Obtain an iterator for the hash set
Iterator iterator = m.keySet().iterator();

// Display the elements in the hash set
while (iterator.hasNext()) {
System.out.println("key: " + iterator.next() + "");
}
}
}

OutPut:
key: /home/
key: /home/Andy
key: /home/Andy/Desktop

}}}


Reference:
Java Sorted
比較深入 comparator


沒有留言:

張貼留言