在此程序中,您將學(xué)習(xí)按Java中的值對給定的映射進行排序。
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中的每個項目并打印其鍵和值。