Map按照Key排序和Map按照Value排序
来源:互联网 发布:电工电子技术网络课 编辑:程序博客网 时间:2024/05/18 00:23
Map数组按照Value排序(升序)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class LinkedHashMapSortWithValue {
public static void main(String[] args) throws Exception {
// TODO code application logic here
Map<String, Integer> myMap = new LinkedHashMap();
myMap.put("1", 1);
myMap.put("2", 4);
myMap.put("3", 3);
myMap.put("4", 9);
myMap.put("5", 6);
myMap.put("6", 2);
printMap(myMap);
myMap = sortMap(myMap);
printMap(myMap);
}
private static void printMap(Map map){
System.out.println("===================mapStart==================");
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("===================mapEnd==================");
}
public static Map sortMap(Map oldMap) {
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<java.lang.String, Integer> arg0,
Entry<java.lang.String, Integer> arg1) {
return arg0.getValue() - arg1.getValue();
}
});
Map newMap = new LinkedHashMap();
for (int i = 0; i < list.size(); i++) {
newMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return newMap;
}
}
Map数组按照Key降序和升序排列
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapSortWithKey {
public static void main(String[] args) {
TreeMap<Integer,Integer> map1 = new TreeMap<Integer,Integer>(); //默认的TreeMap升序排列
TreeMap<Integer,Integer> map2= new TreeMap<Integer,Integer>(new Comparator<Integer>(){
/*
* int compare(Object o1, Object o2) 返回一个基本类型的整型,
* 返回负数表示:o1 小于o2,
* 返回0 表示:o1和o2相等,
* 返回正数表示:o1大于o2。
*/
public int compare(Integer a,Integer b){
return b-a;
}
});
map2.put(1,2);
map2.put(2,4);
map2.put(7, 1);
map2.put(5,2);
System.out.println("Map2="+map2);
map1.put(1,2);
map1.put(2,4);
map1.put(7, 1);
map1.put(5,2);
System.out.println("map1="+map1);
}
}
0 0
- Map按照Key排序和Map按照Value排序
- Map分别按照Key和value排序
- Map按照key和value进行排序
- 关联容器map按照value排序或者按照key排序
- map 按照value排序
- Java Map集合按照key和value排序之法
- map的排序(按照key值和按照value值)
- Map按照Value值排序
- Java Map按照Value 排序
- java map按照value排序
- map中的元素按照key,value值排序
- [整理]关于map的简单操作和按照Key与value的排序
- java按照map的value排序
- C++ map容器 按照value值排序
- c++对map按照value排序
- Map按照Value值进行排序
- C++ map容器 按照value值排序
- Map按照Value值进行排序
- 输入一个正整数,按照从小到大的顺序输出它的所有质数的因子
- 关于多选框 反选问题
- android-支持多种屏幕[分组资源类型] 十
- Android Debug Database
- 常用页面布局技术
- Map按照Key排序和Map按照Value排序
- .net中的序列化
- QML创建一个带多个下拉输入框的窗口(ComboBox)
- exception handling of Python
- PHP内核探索之变量(5)- session的基本原理
- 解决:Dropzone.js的图片拖拽上传保存本地文件夹
- Eclipse CDT中出现 Nothing to build for XXX 的问题
- PHP 全局变量 局部变量 静态变量 常量
- 书写规则