Java对map进行排序并生成序号
2017-11-13 14:43
375 查看
最近做的项目有这样一个需求:要求对map中的值进行排序并生成序号。如果值相等则序号不变;如果不相等序号为该数数值在所有元素中的索引。如下表所示:
Key(String) | Value(Float) | Idx |
---|---|---|
23 | 12.4 | 1 |
10 | 3.2 | 2 |
11 | 2.2 | 3 |
9 | 2.2 | 3 |
1 | 1.9 | 5 |
6 | 0.5 | 6 |
public static Integer getSort(Map<String, Float> hashMap, String string) { // 转换 ArrayList<Entry<String, Float>> arrayList = new ArrayList<Map.Entry<String, Float>>( hashMap.entrySet()); // 排序 Collections.sort(arrayList, new Comparator<Map.Entry<String, Float>>() { public int compare(Map.Entry<String, Float> map1, Map.Entry<String, Float> map2) { return ((map2.getValue() - map1.getValue() == 0) ? 0 : (map2 .getValue() - map1.getValue() > 0) ? 1 : -1); } }); Map<String, Integer> idxex = new HashMap<String, Integer>(); // 输出 int size = 1; for (int i = 0; i < arrayList.size(); i++) { Entry<String, Float> entry = arrayList.get(i); if (i > 0) { float curr = arrayList.get(i).getValue(); float last = arrayList.get(i - 1).getValue(); if (curr != last) { size = i; idxex.put(entry.getKey(), (i + 1)); size++; } else { idxex.put(entry.getKey(), size); } } else { idxex.put(entry.getKey(), size); } } for (Map.Entry<String, Integer> entry : idxex.entrySet()) { String key = entry.getKey(); if (string.equals(key)) { return entry.getValue(); } } return 0; }
相关文章推荐
- (java)根据map中value进行排序
- Java中对list map根据map某个key值进行排序的方法
- java的Map集合中按value值进行排序输出的实例代码
- java中对map根据value进行排序
- java中list里面存放map,根据map中的某一个字段进行排序
- java中list里面存放map,根据map中的某一个字段进行排序
- Java如何对Map进行排序详解
- Java基础 —— 根据 Key 或是 Value 对 Map 进行排序
- java.unit工具类的使用(Arrays类进行排序,查找;Random生成随机数)
- Java Map按Key值进行排序
- 在java中怎样对一个Map进行排序(java 8之前的版本)
- java如何对map进行排序详解(map集合的使用)
- Java中Map根据键值(key)或者值(value)进行排序实现
- Java中Map根据键值(key)或者值(value)进行排序实现
- java排序,随机生成一个数组,对其进行排序,偶数在前奇数在后,偶数从小到大排,奇数从大到小排
- Java 对Map进行排序的实现方法
- 对Java的Map的Value字段进行排序
- 【JAVA语言基础】map以value进行排序
- java如何对map进行排序详解(map集合的使用)
- Java 中 Map 根据键值 (key) 或者值 (value) 进行排序实现