如何在 Java 中对 HashMap 进行排序 [英] How to sort a HashMap in Java

查看:33
本文介绍了如何在 Java 中对 HashMap 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何对 HashMap 进行排序?

How are we able to sort a HashMap<key, ArrayList>?

我想根据 ArrayList 中的值进行排序.

I want to sort on the basis of a value in the ArrayList.

推荐答案

你必须使用 HashMap 吗?如果您只需要地图界面,请使用 树形图

Do you have to use a HashMap? If you only need the Map Interface use a TreeMap

如果您想通过比较 HashMap 中的值进行排序.您必须编写代码来执行此操作,如果您想在对 HashMap 的值进行排序后执行此操作:

If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:

Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);

// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());

Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));

for (Person p : peopleByAge) {
    System.out.println(p.getName() + "	" + p.getAge());
}

如果您想经常访问这个排序列表,那么您可以将您的元素插入到 HashMap> 中,尽管集合和列表的语义有点不同.

If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>, though the semantics of sets and lists are a bit different.

这篇关于如何在 Java 中对 HashMap 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆