亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Java 菜鳥教程

Java 流程控制

Java 數(shù)組

Java 面向?qū)ο?I)

Java 面向?qū)ο?II)

Java 面向?qū)ο?III)

Java 異常處理

Java 列表(List)

Java Queue(隊列)

Java Map集合

Java Set集合

Java 輸入輸出(I/O)

Java Reader/Writer

Java 其他主題

Java程序按值對映射進行排序

Java 實例大全

在此程序中,您將學(xué)習(xí)按Java中的值對給定的映射進行排序。

示例:按值對map排序

import java.util.*;

public class SortMap {

    public static void main(String[] args) {

        LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
        capitals.put("Nepal", "Kathmandu");
        capitals.put("India", "New Delhi");
        capitals.put("United States", "Washington");
        capitals.put("England", "London");
        capitals.put("Australia", "Canberra");

        Map<String, String> result = sortMap(capitals);

        for (Map.Entry<String, String> entry : result.entrySet())
        {
            System.out.print("Key: " + entry.getKey());
            System.out.println(" Value: " + entry.getValue());
        }
    }

    public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) {
        List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet());

        Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));

        LinkedHashMap<String, String> result = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : capitalList)
        {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;
    }
}

運行該程序時,輸出為:

Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington

在上面的程序中,我們將LinkedHashMap國家/地區(qū)及其各自的首都,存儲在變量capitals中。

我們有一個方法sortMap(),它采用雙向鏈表并返回排序后的雙向鏈表。

在方法內(nèi)部,我們將哈希映射轉(zhuǎn)換為列表capitalList。然后,我們使用sort()方法,該方法接受一個列表和一個比較器。

在我們的實例中,比較器是將(o1,o2)-> o1.getValue().compareTo(o2.getValue())兩個列表o1和o2中的值進行比較的lambda表達式。

運算后,我們得到排序列表capitalList。然后,我們只需將列表轉(zhuǎn)換為LinkedHashMap結(jié)果并返回即可。

回到main()方法中,我們遍歷map中的每個項目并打印其鍵和值。

Java 實例大全