按值的字母顺序对 HashMap 进行排序

发布于 2024-10-01 20:34:14 字数 171 浏览 2 评论 0原文

我有一个 HashMap,其中 Object 是学生的 ID,Student 是来自 Student 的对象。

如何通过学生姓名 student->getName() 重新调用 HashMap?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

天煞孤星 2024-10-08 20:34:14

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

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

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

HashMaps are intrinsically unordered and cannot be sorted.

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

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

丑丑阿 2024-10-08 20:34:14

您可能无法对 HashMap 进行排序,但您当然可以做一些提供相同效果的事情。我能够对 HashMap进行排序通过使用 Java 重访 博客。同样的原则也适用于 HashMap。 object:

/*
 * 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;
}

要调用此方法,我使用:

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

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

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 Javarevisited blog. The same principle would apply to a HashMap <String, String> object:

/*
 * 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

小…红帽 2024-10-08 20:34:14

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

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());
    }
});

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

祝你好运。

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.

情场扛把子 2024-10-08 20:34:14

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

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

如果您同时需要恒定时间查找和按值排序的集合,那么您可能需要维护映射和集合。

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 SortedSet and creating a comparator that sorts by the names.

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.

风启觞 2024-10-08 20:34:14

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

然后你可以将Map的每个元素以此类的形式放入一个ArrayList中,最后使用比较器对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());
}

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;
  }    
}

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

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<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

    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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文