This question already has answers here:
Sort a Map<Key, Value> by values
(57个答案)
在11个月前关闭。
我们如何对
我想根据
如果要经常访问此排序列表,则可以将元素插入
(57个答案)
在11个月前关闭。
我们如何对
HashMap<key, ArrayList>
进行排序?我想根据
ArrayList
中的值进行排序。 最佳答案
您必须使用HashMap吗?如果只需要Map Interface,请使用TreeMap
如果要通过比较HashMap中的值进行排序。您必须编写代码才能执行此操作,如果要执行此操作,则可以对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() + "\t" + p.getAge());
}
如果要经常访问此排序列表,则可以将元素插入
HashMap<TreeSet<Person>>
,尽管集合和列表的语义有些不同。关于java - 如何在Java中对HashMap进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57358757/