Java程序 通过值对LinkedHashMap进行排序
LinkedHashMap就像HashMap一样,有一个额外的功能,即维护插入其中的元素的顺序。HashMap提供了快速插入、搜索和删除的优势,但是它从来没有保持插入的轨迹和顺序,而LinkedHashMap提供了元素可以按照插入的顺序被访问。
因此,LinkedHashMap是HashMap的子类。现在,在LinkedHashMap中必须保持插入顺序,所以要将LinkedHashMap转换为一个列表,然后打印这个列表,其中的值是按顺序排列的。
演示:
输入 : LinkedHashMap = {{"for", 2}, {"Geek", 3}, {"Geeks", 1}}。
输出:
Key - > Geeks : value -> 1
Key - > for : value -> 2
Key - > Geek : value ->3
步骤:
1.创建一个LinkedHashMap类的对象,该对象被声明为Integer和String类型。
2.使用put()方法将元素添加到上述地图创建的对象中。这里的元素是键-值对。
3.使用entrySet()方法从地图中获取上述所有条目并将其转换为一个列表。
4.使用自定义比较器对列表中的值进行排序。
5.现在使用Collections类的排序方法,里面我们使用一个自定义的比较器来比较一个地图的值。
6.使用for each循环打印上述列表对象。
实现:
示例
// java Program to Sort LinkedHashMap by Values
// Importing all classes
// from java.util package
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an object of LinkedHashMap Class
// Declaring object of Integer and String type
LinkedHashMap<String, Integer> map
= new LinkedHashMap<>();
// Adding elements to the object of Map
// using the put() method
// Elements here are key-value pairs
map.put("for", 2);
map.put("Geek", 3);
map.put("Geeks", 1);
// Now, getting all entries from map and
// convert it to a list using entrySet() method
List<Map.Entry<String, Integer> > list
= new ArrayList<Map.Entry<String, Integer> >(
map.entrySet());
// Using collections class sort method
// and inside which we are using
// custom comparator to compare value of map
Collections.sort(
list,
new Comparator<Map.Entry<String, Integer> >() {
// Comparing two entries by value
public int compare(
Map.Entry<String, Integer> entry1,
Map.Entry<String, Integer> entry2)
{
// Subtracting the entries
return entry1.getValue()
- entry2.getValue();
}
});
// Iterating over the sorted map
// using the for each method
for (Map.Entry<String, Integer> l : list) {
// Printing the sorted map
// using getKey() and getValue() methods
System.out.println("Key ->"
+ " " + l.getKey()
+ ": Value ->"
+ l.getValue());
}
}
}
输出
Key -> Geeks: Value ->1
Key -> for: Value ->2
Key -> Geek: Value ->3