java list<map> 排序
发布网友
发布时间:2022-04-28 23:54
我来回答
共2个回答
热心网友
时间:2022-06-25 21:05
用我这个排序不是更简单么
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class $ {
public static void main(String[] args) {
List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
Map<Object, Object> map = new HashMap<Object, Object>();
Map<Object, Object> map1 = new HashMap<Object, Object>();
Map<Object, Object> map2 = new HashMap<Object, Object>();
Map<Object, Object> map3 = new HashMap<Object, Object>();
map.put("number", 1);
map1.put("number", 2);
map2.put("number", 4);
map3.put("number", 3);
list.add(map);
list.add(map1);
list.add(map2);
list.add(map3);
Collections.sort(list, new Comparator<Map<Object, Object>>() {
public int compare(Map<Object, Object> o1, Map<Object, Object> o2) {
int map1value = (Integer) o1.get("number");
int map2value = (Integer) o2.get("number");
return map1value - map2value;
}
});
System.out.println(list);
}
}
追问您回答的对,现在我想问下用冒泡排序的话,怎么才能写出来呢?谢谢你
追答
不好意思,才看见,你这个不适合用冒泡排序做。实现起来非常麻烦,冒泡的,建议你理解的概念,就可以了。
上面代码的30行~40行,用下面的代替
System.out.println(list);
for (int i = 0; i < list.size(); i++) {
Map<Object, Object> tmp0 = list.get(i);
int number0 = (Integer) tmp0.get("number");
Map<Object, Object> tmp = null;
for (int j = i; j < list.size(); j++) {
Map<Object, Object> tmp1 = list.get(j);
int number1 = (Integer) tmp1.get("number");
if (number0 > number1) {
tmp = tmp0;
list.set(i, list.get(j));
list.set(j, tmp);
}
}
}
System.out.println(list);
这个是用冒泡排序实现的,你对比下吧,哪个简单?
你出现的问题是:对象间用等号赋值,那么就让这两个对象指向了同一个内存地址,也就是等同的,即,可以理解为对东一个文件创建两个快捷方式,但实际指向的还是同一个文件。利用list里面的set方法来赋值
热心网友
时间:2022-06-25 21:05
带Tree的类多好啊,排序方便啊