Here you can find the source of sortedMap(Map
Parameter | Description |
---|---|
map | a parameter |
comparator | a parameter |
public static <K, V> Map<K, V> sortedMap(Map<K, V> map, Comparator<K> comparator)
//package com.java2s; //License from project: Open Source License import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main { /**//from w w w .jav a2 s. c o m * Method to sort a map based on the comparator * * @param map * @param comparator * @return {@link Map<K, V>} */ public static <K, V> Map<K, V> sortedMap(Map<K, V> map, Comparator<K> comparator) { if (map != null && comparator != null) { Map<K, V> returnValue = new HashMap<>(); List<K> list = new ArrayList<>(); for (K key : map.keySet()) { list.add(key); } Collections.sort(list, comparator); for (int i = 0; i < list.size(); i++) { K key = list.get(i); returnValue.put(key, map.get(key)); } return returnValue; } return null; } }