2008年10月17日 星期五

[Java]用Arraylist來排序和過濾陣列(Collections)





import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashSet;

import java.util.List;



public class SortListDemo {



public static class StringComparator> implements Comparator {



public int compare(T o1, T o2) {

if (o1 == null && o2 == null) {

return 0;

} else if (o1 == null) {

return -1;

} else if (o2 == null) {

return 1;

} else {

return o1.compareTo(o2);

}

}

}



public static void main(String[] args) {

List list = new ArrayList();

list.add("111-1111");

list.add("131-1111");

list.add("111-1111");

list.add("131-1111");

list.add("121-1221");

list.add("111-1111");

list.add("111-1111");



SortListDemo sortList = new SortListDemo();



Object[] result = sortList.SortStringList(sortList.removeIterance(list)).toArray();



for (int i = 0; i < result.length; i++) {

System.out.println(result[i]);

}

}



private List removeIterance(List list) {

ArrayList result = new ArrayList();

if (list != null && list.size() > 0) {

HashSet set = new HashSet();

set.addAll(list);

result.addAll(set);

}

return result;

}



private List SortStringList(List list) {

Comparator comp = new StringComparator();

Collections.sort(list, comp);

return list;

}

}



沒有留言:

張貼留言