java集合排序
如何给Java中List集合排序呢?前端时间在工作中遇到类似于给这样的结构排序List<Map<String,String>>>按照其中Map中的某个key值排序呢?
集合产生如下:
<span style="font-size:18px;">public void sortList(){ List<List<Map<String,String>>> list = new ArrayList<List<Map<String,String>>>(); int group = 0; for(int i =0;i<10;i++){ List<Map<String,String>> tempList = new ArrayList<Map<String,String>>(); group = new Random().nextInt(45); for(int j = 0;j<2;j++){ Map<String,String> map = new HashMap<String,String>(); map.put("group", group+""); tempList.add(map); } list.add(tempList); } for(int i=0;i<list.size();i++){ System.out.println("group ==" + list.get(i).get(0).get("group")); } }</span>
其中group的顺序为:
<span style="font-size:24px;">group ==43 group ==25 group ==28 group ==32 group ==19 group ==20 group ==25 group ==21 group ==24 group ==36</span>
排序函数为:
<span style="font-size:18px;">public List<List<Map<String, String>>> sortResList(List<List<Map<String, String>>> list) { if (list != null && list.size() > 0) { for (int i = 0; i <list.size(); i++) { for (int j = i; j < list.size(); j++) { int tempGroup = Integer.valueOf(list.get(i).get(0).get("group")); int tempGroup1 = Integer.valueOf(list.get(j).get(0).get("group")); if (tempGroup1 < tempGroup) { <span style="color:#ff0000;">Collections.swap(list, i, j);</span> } } } } return list; }</span>
这次排序函数用了冒泡排序的思想,主要的思想是调用了API的Collections.swap(List<?> list, int i, int j)这个函数,实现排序功能!
<span style="font-size:24px;">排序后的结果为: sort之后的情况 group ==3 group ==9 group ==9 group ==10 group ==12 group ==23 group ==24 group ==36 group ==43 group ==44</span>
------- 路漫漫其修远兮,吾将上下而求索
时间: 2024-10-27 04:42:13