📜  使用Java中的可比较接口按值对 LinkedHashMap 进行排序

📅  最后修改于: 2022-05-13 01:55:49.692000             🧑  作者: Mango

使用Java中的可比较接口按值对 LinkedHashMap 进行排序

LinkedHashMap 就像 HashMap 一样,具有维护插入元素顺序的附加功能。假设您已经在Java中使用了 LinkedHashMap 并了解 LinkedHashMap。

句法:

int compare(T obj) ;

插图:

方法:在使用 Comparable 接口按值对 LinkedHashMap 进行排序时,该接口对实现它的每个类的对象进行了总排序。这种排序称为类的自然排序,类的比较方法称为其自然比较方法。

执行:

例子

Java
Input  : { GEEKS=1, geeks=3, for=2 }
Output : { GEEKS=1, for=2, geeks=3 }

Input  : { 101 = 2, 102 = 9, 103 = 1, 105 = 7 }
Output : { 103 = 1, 101 = 2, 105 = 7, 102 = 9 }


输出
// Java program to sort the values of LinkedHashMap
  
// Importing required classes from
// java.util package
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.*;
  
// Class 
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an LinkedHashMap object
        LinkedHashMap l_map
            = new LinkedHashMap();
  
        // Adding element to LinkedHashSet
        // Custom inputs
        l_map.put("Computer", 1);
        l_map.put("Science", 3);
        l_map.put("Portal", 2);
  
        // Display message
        System.out.print(
            "LinkedHashMap without sorting : ");
  
        // Print the elements of Map in above object
        // just after addition without sorting
        System.out.println(l_map);
  
        // Convert key-value from the LinkedHashMap to List
        // using entryset() method
        List > list
            = new ArrayList >(
                l_map.entrySet());
  
        // Comparable Interface function to
        // sort the values of List
        Collections.sort(
            list,
            new Comparator >() {
                // Comparing entries
                public int compare(
                    Entry entry1,
                    Entry entry2)
                {
                    return entry1.getValue()
                        - entry2.getValue();
                }
            });
  
        // Clear the above LinkedHashMap
        // using clear() method
        l_map.clear();
  
        // Iterating over elements using for each loop
        for (Map.Entry entry : list) {
  
            // Put all sorted value back to the
            // LinkedHashMap
            l_map.put(entry.getKey(), entry.getValue());
        }
  
        // Display and print
        // the sorted value of LinkedHashMap
        System.out.println(
            "LinkedHashMap after sorting   : " + l_map);
    }
}