Java 按值排序HashMap

Java 按值排序HashMap,java,sorting,hashmap,Java,Sorting,Hashmap,我需要根据存储在HashMap中的值对HashMap进行排序。HashMap包含储存在手机中的联系人姓名 我还需要在对值进行排序后立即对键进行自动排序,或者可以说键和值绑定在一起,因此值中的任何更改都应该反映在键中 HashMap<Integer,String> map = new HashMap<Integer,String>(); map.put(1,"froyo"); map.put(2,"abby"); map.put(3,"denver"); map.put(4

我需要根据存储在HashMap中的值对HashMap进行排序。
HashMap
包含储存在手机中的联系人姓名

我还需要在对值进行排序后立即对键进行自动排序,或者可以说键和值绑定在一起,因此值中的任何更改都应该反映在键中

HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"froyo");
map.put(2,"abby");
map.put(3,"denver");
map.put(4,"frost");
map.put(5,"daisy");

基本上你没有。
HashMap
基本上是无序的。您在订购中可能看到的任何模式都不应依赖

有一些已排序的映射,如
TreeMap
,但它们传统上是按键排序,而不是按值排序。按值排序是相对不常见的,尤其是当多个键可以具有相同的值时

你能为你要做的事情提供更多的背景吗?如果您实际上只存储按键的数字(作为字符串),那么像
TreeSet
这样的
SortedSet
可能适合您


或者,您可以存储封装在单个类中的两个独立集合,以便同时更新这两个集合?

假设使用Java,您可以按如下方式对hashmap进行排序:

public LinkedHashMap<Integer, String> sortHashMapByValues(
        HashMap<Integer, String> passedMap) {
    List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
    List<String> mapValues = new ArrayList<>(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);

    LinkedHashMap<Integer, String> sortedMap =
        new LinkedHashMap<>();

    Iterator<String> valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
        String val = valueIt.next();
        Iterator<Integer> keyIt = mapKeys.iterator();

        while (keyIt.hasNext()) {
            Integer key = keyIt.next();
            String comp1 = passedMap.get(key);
            String comp2 = val;

            if (comp1.equals(comp2)) {
                keyIt.remove();
                sortedMap.put(key, val);
                break;
            }
        }
    }
    return sortedMap;
}
公共LinkedHashMap sortHashMapByValues(
HashMap passedMap){
List mapKeys=new ArrayList(passedMap.keySet());
List mapValues=new ArrayList(passedMap.values());
Collections.sort(映射值);
Collections.sort(映射键);
LinkedHashMap分类地图=
新建LinkedHashMap();
迭代器值It=mapValues.Iterator();
while(valueIt.hasNext()){
字符串val=valueIt.next();
迭代器keyIt=mapKeys.Iterator();
while(keyIt.hasNext()){
整数key=keyIt.next();
字符串comp1=passedMap.get(键);
字符串comp2=val;
如果(comp1等于(comp2)){
keyIt.remove();
分类地图放置(键,val);
打破
}
}
}
返回分拣的DMAP;
}

这只是一个开始的例子。这种方法更有用,因为它可以对HashMap进行排序,并保留重复的值。

试试下面的代码,它对我来说很好。您可以选择升序和降序

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}
import java.util.Collections;
导入java.util.Comparator;
导入java.util.HashMap;
导入java.util.LinkedHashMap;
导入java.util.LinkedList;
导入java.util.List;
导入java.util.Map;
导入java.util.Map.Entry;
公共类SortMapByValue
{
公共静态布尔值ASC=true;
公共静态布尔DESC=false;
公共静态void main(字符串[]args)
{
//创建虚拟未排序贴图
Map unsortMap=newhashmap();
不排序图。放置(“B”,55);
反排序图。放置(“A”,80);
反排序图。放置(“D”,20);
反排序图。放置(“C”,70);
System.out.println(“排序前……”);
printMap(unsortMap);
System.out.println(“升序排序后……”);
Map sortedMapAsc=排序比较程序(unsortMap,ASC);
印刷地图(分类地图);
System.out.println(“排序后定义顺序……”);
Map sortedMapDesc=sortByComparator(反排序图,DESC);
打印地图(sortedMapDesc);
}
私有静态映射sortByComparator(映射非排序映射,最终布尔顺序)
{
List=新的LinkedList(unsortMap.entrySet());
//根据值对列表进行排序
Collections.sort(list,newcomparator()
{
公共整数比较(条目o1,
入口(氧气)
{
如果(订单)
{
返回o1.getValue().compareTo(o2.getValue());
}
其他的
{
返回o2.getValue().compareTo(o1.getValue());
}
}
});
//借助LinkedList维护插入顺序
Map sortedMap=new LinkedHashMap();
用于(条目:列表)
{
sortedMap.put(entry.getKey(),entry.getValue());
}
返回分拣的DMAP;
}
公共静态无效打印地图(地图地图)
{
for(条目:map.entrySet())
{
System.out.println(“Key:+entry.getKey()+”值:+entry.getValue());
}
}
}
编辑:版本2

为每个etc使用了新的java特性,比如stream

如果值相同,地图将按键排序

import java.util.*;
导入java.util.Map.Entry;
导入java.util.stream.collector;
公共类SortMapByValue
{
私有静态布尔ASC=true;
私有静态布尔DESC=false;
公共静态void main(字符串[]args)
{
//创建虚拟未排序贴图
Map unsortMap=newhashmap();
不排序图。放置(“B”,55);
反排序图。放置(“A”,20);
反排序图。放置(“D”,20);
反排序图。放置(“C”,70);
System.out.println(“排序前……”);
printMap(unsortMap);
System.out.println(“升序排序后……”);
Map sortedMapAsc=sortByValue(反排序映射,ASC);
印刷地图(分类地图);
System.out.println(“按降序排序后……”);
Map sortedMapDesc=sortByValue(反排序映射,DESC);
打印地图(sortedMapDesc);
}
私有静态映射sortByValue(映射非排序映射,最终布尔顺序)
{
List=新的LinkedList(unsortMap.entrySet());
//根据值对列表进行排序
list.sort((o1,o2)->order?o1.getValue().compareTo(o2.getValue())==0
?o1.getKey().与(o2.getKey())进行比较
:o1.getValue().compareTo(o2.getValue()):o2.getValue().compareTo(o1.getValue())==0
?o2.getKey()。与(o1.getKey())比较
:o2.getValue().compareTo(o1.getValue());
return list.stream().collect(Collectors.toMap(Entry::getKey,Entry::getValue,(a,b)->b,LinkedHashMap::new));
}
私有静态void打印映射(映射映射)
{
map.forEach((键,值)->系统。
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}
 import java.util.*;
 import java.util.Map.Entry;
 import java.util.stream.Collectors;

 public class SortMapByValue

 {
    private static boolean ASC = true;
    private static boolean DESC = false;
    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 20);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByValue(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descending order......");
        Map<String, Integer> sortedMapDesc = sortByValue(unsortMap, DESC);
        printMap(sortedMapDesc);
    }

    private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap, final boolean order)
    {
        List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet());

        // Sorting the list based on values
        list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0
                ? o1.getKey().compareTo(o2.getKey())
                : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
                ? o2.getKey().compareTo(o1.getKey())
                : o2.getValue().compareTo(o1.getValue()));
        return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));

    }

    private static void printMap(Map<String, Integer> map)
    {
        map.forEach((key, value) -> System.out.println("Key : " + key + " Value : " + value));
    }
}
package SortedSet;

import java.util.*;

public class HashMapValueSort {
public static void main(String[] args){
    final Map<Integer, String> map = new HashMap<Integer,String>();
    map.put(4,"Mango");
    map.put(3,"Apple");
    map.put(5,"Orange");
    map.put(8,"Fruits");
    map.put(23,"Vegetables");
    map.put(1,"Zebra");
    map.put(5,"Yellow");
    System.out.println(map);
    final HashMapValueSort sort = new HashMapValueSort();
    final Set<Map.Entry<Integer, String>> entry = map.entrySet();
    final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            String value1 = o1.getValue();
            String value2 = o2.getValue();
            return value1.compareTo(value2);
        }
    };
    final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
    sortedSet.addAll(entry);
    final Map<Integer,String> sortedMap =  new LinkedHashMap<Integer, String>();
    for(Map.Entry<Integer, String> entry1 : sortedSet ){
        sortedMap.put(entry1.getKey(),entry1.getValue());
    }
    System.out.println(sortedMap);
}
}
public static TreeMap<String, String> sortMap(HashMap<String, String> passedMap, String byParam) {
    if(byParam.trim().toLowerCase().equalsIgnoreCase("byValue")) {
        // Altering the (key, value) -> (value, key)
        HashMap<String, String> newMap =  new HashMap<String, String>();
        for (Map.Entry<String, String> entry : passedMap.entrySet()) {
            newMap.put(entry.getValue(), entry.getKey());
        }
        return new TreeMap<String, String>(newMap);
    }
    return new TreeMap<String, String>(passedMap);
}
Map<Integer, String> sortedMap = 
     unsortedMap.entrySet().stream()
    .sorted(Entry.comparingByValue())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                              (e1, e2) -> e1, LinkedHashMap::new));
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

public class CollectionsSort {

    /**
     * @param args
     */`enter code here`
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CollectionsSort colleciotns = new CollectionsSort();

        List<combine> list = new ArrayList<combine>();
        HashMap<String, Integer> h = new HashMap<String, Integer>();
        h.put("nayanana", 10);
        h.put("lohith", 5);

        for (Entry<String, Integer> value : h.entrySet()) {
            combine a = colleciotns.new combine(value.getValue(),
                    value.getKey());
            list.add(a);
        }

        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

    public class combine implements Comparable<combine> {

        public int value;
        public String key;

        public combine(int value, String key) {
            this.value = value;
            this.key = key;
        }

        @Override
        public int compareTo(combine arg0) {
            // TODO Auto-generated method stub
            return this.value > arg0.value ? 1 : this.value < arg0.value ? -1
                    : 0;
        }

        public String toString() {
            return this.value + " " + this.key;
        }
    }

}
   /**
     * sort HashMap<String, CustomData> by value
     * CustomData needs to provide compareTo() for comparing CustomData
     * @param map
     */

    public void sortHashMapByValue(final HashMap<String, CustomData> map) {
        ArrayList<String> keys = new ArrayList<String>();
        keys.addAll(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                CustomData val1 = map.get(lhs);
                CustomData val2 = map.get(rhs);
                if (val1 == null) {
                    return (val2 != null) ? 1 : 0;
                } else if (val1 != null) && (val2 != null)) {
                    return = val1.compareTo(val2);
                }
                else {
                    return 0;
                }
            }
        });

        for (String key : keys) {
            CustomData c = map.get(key);
            if (c != null) {
                Log.e("key:"+key+", CustomData:"+c.toString());
            } 
        }
    }
TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
for (Map.Entry entry : map.entrySet()) {
    sortedMap.put((String) entry.getValue(), (Integer)entry.getKey());
}
package com.naveen.hashmap;

import java.util.*;
import java.util.Map.Entry;

public class SortBasedonValues {

    /**
     * @param args
     */
    public static void main(String[] args) {

        HashMap<String, Integer> hm = new HashMap<String, Integer>();
        hm.put("Naveen", 2);
        hm.put("Santosh", 3);
        hm.put("Ravi", 4);
        hm.put("Pramod", 1);
        Set<Entry<String, Integer>> set = hm.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
                set);
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        for (Entry<String, Integer> entry : list) {
            System.out.println(entry.getValue());

        }

    }
}
map.entrySet().stream()
                .sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))
                .forEach(k -> System.out.println(k.getKey() + ": " + k.getValue()));
public class ValueSortedMap<K extends Comparable, V extends Comparable> extends TreeMap<K, V> {

    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Entry<K, V>> originalEntries = super.entrySet();
        Set<Entry<K, V>> sortedEntry = new TreeSet<Entry<K, V>>(new Comparator<Entry<K, V>>() {
            @Override
            public int compare(Entry<K, V> entryA, Entry<K, V> entryB) {
                int compareTo = entryA.getValue().compareTo(entryB.getValue());
                if(compareTo == 0) {
                    compareTo = entryA.getKey().compareTo(entryB.getKey());
                }
                return compareTo;
            }
        });
        sortedEntry.addAll(originalEntries);
        return sortedEntry;
    }

    @Override
    public Collection<V> values() {
        Set<V> sortedValues = new TreeSet<>(new Comparator<V>(){
            @Override
            public int compare(V vA, V vB) {
                return vA.compareTo(vB);
            }
        });
        sortedValues.addAll(super.values());
        return sortedValues;
    }
}
public class ValueSortedMapTest {

    @Test
    public void basicTest() {
        Map<String, Integer> sortedMap = new ValueSortedMap<>();
        sortedMap.put("A",3);
        sortedMap.put("B",1);
        sortedMap.put("C",2);

        Assert.assertEquals("{B=1, C=2, A=3}", sortedMap.toString());
    }

    @Test
    public void repeatedValues() {
        Map<String, Double> sortedMap = new ValueSortedMap<>();
        sortedMap.put("D",67.3);
        sortedMap.put("A",99.5);
        sortedMap.put("B",67.4);
        sortedMap.put("C",67.4);

        Assert.assertEquals("{D=67.3, B=67.4, C=67.4, A=99.5}", sortedMap.toString());
    }

}