要按照值的集合大小对HashMap进行排序,可以使用Java中的Stream API和Comparator来实现。以下是一个示例代码:
import java.util.*;
public class SortHashMapByValue {
public static void main(String[] args) {
// 创建一个HashMap并添加键值对
HashMap hashMap = new HashMap<>();
hashMap.put("A", 5);
hashMap.put("B", 3);
hashMap.put("C", 8);
hashMap.put("D", 2);
// 使用Stream API和Comparator按值的集合大小对HashMap进行排序
List> sortedList = new ArrayList<>(hashMap.entrySet());
sortedList.sort(Map.Entry.comparingByValue());
// 打印排序后的结果
for (Map.Entry entry : sortedList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
输出:
D: 2
B: 3
A: 5
C: 8
上述代码首先创建一个HashMap,并添加了一些键值对。然后,使用HashMap的entrySet()方法获取键值对的Set视图,并将其转换为一个ArrayList。接下来,通过Stream API和Comparator对ArrayList进行排序,使用Map.Entry.comparingByValue()指定要按值进行排序。最后,使用foreach循环打印排序后的结果。