介绍
在 Java 中,Map 默认是无序的,并以键值对的形式存储数据。通常需要根据值对它们进行排序,以便基于值做出决策。在这个逐步的实验中,我们将学习如何根据值对 Java Map 进行排序。
在 Java 中,Map 默认是无序的,并以键值对的形式存储数据。通常需要根据值对它们进行排序,以便基于值做出决策。在这个逐步的实验中,我们将学习如何根据值对 Java Map 进行排序。
首先,我们将创建一个包含学生姓名和身高(以厘米为单位)的 Map,以便理解如何在 Java 中对 Map 进行排序。
import java.util.*;
public class MapSortingDemo {
public static void main(String args[]) {
Map<String, Integer> students = new HashMap<>();
students.put("Student 1", 159);
students.put("Student 2", 147);
students.put("Student 3", 183);
students.put("Student 4", 167);
students.put("Student 5", 173);
}
}
要根据值对 Map 进行排序,我们需要从 Map.entrySet()
创建一个 List。该方法返回 Map 中的所有键值对。当排序依赖于多个参数时,Comparator 函数就派上用场了。在 Comparator 函数中,return student1.getValue().compareTo(student2.getValue());
决定了排序的方式,即按值排序,这将根据值对 Map 进行排序。
List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());
Collections.sort(studentList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> student1, Map.Entry<String, Integer> student2) {
return student1.getValue().compareTo(student2.getValue());
}
});
在控制台中显示排序后的 Map。
for (Map.Entry<String, Integer> student : studentList) {
System.out.println(student.getKey() + " " + student.getValue());
}
我们也可以使用 Lambda 表达式根据值对 Map 进行排序,这是一种更简洁高效的方式。
List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());
studentList.sort((student1, student2) -> student1.getValue().compareTo(student2.getValue()));
在控制台中显示排序后的 Map。
studentList.forEach(student -> System.out.println(student.getKey() + " " + student.getValue()));
类似地,我们可以根据键对 Map 进行排序。在 Comparator 函数中,return student1.getKey().compareTo(student2.getKey());
决定了排序的方式,即按键排序。
List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());
Collections.sort(studentList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> student1, Map.Entry<String, Integer> student2) {
return student1.getKey().compareTo(student2.getKey());
}
});
在控制台中显示排序后的 Map。
for (Map.Entry<String, Integer> student : studentList) {
System.out.println(student.getKey() + " " + student.getValue());
}
我们也可以使用 Lambda 表达式根据键对 Map 进行排序,这是一种更简洁高效的方式。
List<Map.Entry<String, Integer>> studentList = new ArrayList<>(students.entrySet());
studentList.sort((student1, student2) -> student1.getKey().compareTo(student2.getKey()));
在控制台中显示排序后的 Map。
studentList.forEach(student -> System.out.println(student.getKey() + " " + student.getValue()));
在本实验中,我们学习了如何使用 Collections.sort()
方法和 Comparator
函数对 Java Map 根据值进行排序,以及如何使用 Lambda 表达式实现排序。我们还学习了如何根据键对 Map 进行排序。根据值对 Map 排序在许多场景中非常有用,例如排名或基于优先级的操作。