日期:2014-05-20 浏览次数:20767 次
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
public class Test009 {
public static void main(String[] args) {
ArrayList<Data> list = initData();
System.out.println("before sort");
System.out.println(list);
list = sort(list);
System.out.println("after sort");
System.out.println(list);
}
static ArrayList<Data> initData() {
ArrayList<Data> list = new ArrayList<Data>();
list.add(new Data(3, "dd"));
list.add(new Data(2, "xx"));
list.add(new Data(10, "dd"));
list.add(new Data(6, "mm"));
list.add(new Data(5, "dd"));
list.add(new Data(6, "gg"));
list.add(new Data(7, "gg"));
return list;
}
static ArrayList<Data> sort(ArrayList<Data> list) {
LinkedHashMap<String, ArrayList<Integer>> map = new LinkedHashMap<String, ArrayList<Integer>>();
for (Data data : list) {
String key = data.getNum();
if (map.containsKey(key)) {
map.get(key).add(data.getDate());
} else {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(data.getDate());
map.put(key, arrayList);
}
}
for (Data data : list) {
Collections.sort(map.get(data.getNum()));
}
String[] nums = new String[map.size()];
map.keySet().toArray(nums);
for (int i = 0; i < nums.length; ++i) {
int num = map.get(nums[i]).get(0);
for (int j = i + 1; j < nums.length; ++j) {
int num2 = map.get(nums[j]).get(0);
if (num > num2) {
String temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
System.out.println(map);
ArrayList<Data> resultList = new ArrayList<Data>();
for (String num : nums) {
ArrayList<Integer> indexList = map.get(num);
for (Integer date : indexList) {
resultList.add(new Data(date, num));
}
}
return resultList;
}
}
class Data {
int date;
String num;
public Data(int date, String num) {
super();