求高手解决排序分组问题
有如下数据:
日期 账单号
3 dd
2 xx
10 dd
6 mm
5 dd
6 gg
7 gg
=============================================
需要先根据日期排序(升序),如果有相同的账单号就放在一起,正确的结果如下:
2 xx
3 dd
5 dd
10 dd
6 mm
6 gg
7 gg
============================================== java oracle
[解决办法]
二维数组+冒泡
[解决办法]
楼主这个数据的排序啥意思啊,是数据库的数据还是文件的数据,还是集合的数据。
[解决办法]
第一感觉好像是数据库的数据以为是写sql语句的,数组???排序??
[解决办法]
思路
3 dd dd(3,10,5) dd(3,5,10) xx(2)
2 xx xx(2) xx(2) dd(3,5,10)
10 dd => mm(6) => mm(6) => mm(6)
6 mm gg(6,7) gg(6,7) gg(6,7)
5 dd
6 gg
7 gg
代码
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();
this.date = date;
this.num = num;
}
public int getDate() {
return date;
}
public String getNum() {
return num;
}
@Override
public String toString() {
return date + " " + num;
}
}