Java 按值按字母顺序排列 HashMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4150179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:05:43  来源:igfitidea点击:

Order HashMap alphabetically by value

javasortingcollections

提问by Chiggins

I have a HashMap<Object, Student>where the Object is the ID of the Student, and the Student is an object from Student.

我有一个HashMap<Object, Student>对象是学生的 ID,学生是学生的对象。

How can I resort the HashMap by the Students name, student->getName()?

如何通过学生姓名使用 HashMap student->getName()

采纳答案by SLaks

HashMaps are intrinsically unordered and cannot be sorted.

HashMap 本质上是无序的,无法排序。

Instead, you can use a SortedMapimplementation, such as a TreeMap.
However, even a sorted map can only sort by its keys.

相反,您可以使用SortedMap实现,例如TreeMap
但是,即使是已排序的映射也只能按其键进行排序。

If you want to sort by the values, you'll need to copy them to a sorted list.

如果要按值排序,则需要将它们复制到排序列表中。

回答by Jeff Storey

HashMaps cannot be sorted by their values. A Map is designed for constant time lookups based on the key, so ordering by values should not be necessary. If you need to sort by name, I suggest using a SortedSetand creating a comparator that sorts by the names.

HashMap 不能按它们的值排序。Map 是为基于键的恒定时间查找而设计的,因此不需要按值排序。如果您需要按名称排序,我建议使用 aSortedSet并创建一个按名称排序的比较器。

class StudentComparator implements Comparator<Student> {
    int compare(Student s1, Student s2) {
       return s1.getName().compareTo(s2.getName());
    }
}

If you need both a constant time lookup and a sorted-by-value set, then you may need to maintain a map and a set.

如果您需要一个常数时间查找和一个按值排序的集合,那么您可能需要维护一个映射和一个集合。

回答by Todd

Maps cannot be ordered by values. You can do this, though:

地图不能按值排序。不过,您可以这样做:

Collection<Student> students = map.values();

Collection.sort(new ArrayList<Student>(students)), new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2.getName());
    }
});

Assuming, of course, that you need to iterate over the values. (Why else would you want it ordered like that?)

当然,假设您需要迭代这些值。(否则你为什么要这样订购?)

Good luck.

祝你好运。

回答by will824

I would definitely use a New Class that will store the key and the Object.

我肯定会使用一个新类来存储密钥和对象。

Then you can put every element of the Map into an ArrayList in the form of this class, and finally use a comparator to sort the ArrayList, afterwards you simply build a new Map. Code will be something like this:

然后你就可以把Map的每一个元素以这个类的形式放到一个ArrayList中,最后用一个comparator对ArrayList进行排序,之后就简单的新建一个Map了。代码将是这样的:

Map<Object, Student> valueMap = new LinkedHashMap<String, String>();
List<Student> pairValueList = new ArrayList<PairValue>();

PairValue p;
for (Map.Entry<Object, Student> entry : map.entrySet()) {
  Object key = entry.getKey();
  Student value = entry.getValue();        
  p = new PairValue(key, value);
  pairValueList.add(p);
 }

Collections.sort(pairValueList, new Comparator<PairValue>() {
  @Override
  public int compare(PairValue c1, PairValue c2) {
    return c1.getLabel().compareTo(c2.getLabel());
  }
});

for (PairValue pv : pairValueList) {
  valueMap.put(pv.getValue(), pv.getStudent());
}

The PairValue class

PairValue 类

    class PairValue {    

  private Object value;    
  private Student student;

  public PairValue(Object value, String student) {
    this.value = value;
    this.student= student;
  }

  public String getValue() {
    return value;
  }

  public String getStudent() {
    return student;
  }    
}

Thats the way I solved some similar problem I had in the past. Please Note that the returned map implementation needs to be a LinkedHashMap.

这就是我解决过去遇到的一些类似问题的方式。请注意,返回的地图实现需要是 LinkedHashMap。

回答by Steve HHH

You might not be able to sort a HashMap, but you can certainly do something that provides the same effect. I was able to sort my HashMap <String, Integer> by descending value of the Integer by using the excellent code posted at the Javarevisitedblog. The same principle would apply to a HashMap <String, String> object:

您可能无法对 HashMap 进行排序,但您当然可以做一些提供相同效果的事情。我能够通过使用Javarevisited博客上发布的优秀代码对 Integer 的值进行降序对我的 HashMap <String, Integer> 进行排序。同样的原则也适用于 HashMap <String, String> 对象:

/*
 * Java method to sort Map in Java by value e.g. HashMap or Hashtable
 * throw NullPointerException if Map contains null values
 * It also sort values even if they are duplicates
 */
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
    List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());

    Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {

        @Override
        public int compare(Entry<K, V> o1, Entry<K, V> o2) {
            return o1.getValue().compareTo(o2.getValue());
            // to compare alphabetically case insensitive return this instead
            // o1.getValue().toString().compareToIgnoreCase(o2.getValue().toString()); 
        }
    });

    //LinkedHashMap will keep the keys in the order they are inserted
    //which is currently sorted on natural ordering
    Map<K,V> sortedMap = new LinkedHashMap<K,V>();

    for(Map.Entry<K,V> entry: entries){
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}

To call this method, I use:

要调用此方法,我使用:

Map<String, Integer> sorted = sortByValues(myOriginalHashMapObject);

Read more: http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj

阅读更多:http: //javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj