Map 工具類
阿新 • • 發佈:2018-12-09
map 工具類
key 是否存在
/** * * key是否存在 * @param map * @param key * @param <K> * @param <V> * @return */ public static <K, V> Boolean isExistsInMapByKey(Map<K, V> map, K key) { if (map == null || key == null) { return false; } return map.containsKey(key); }
value 是否存在
/** * Value 是否存在 * @param map * @param object * @param <K> * @param <V> * @return */ public static <K, V> Boolean isExistsInMapByValue(Map<K, V> map, V object) { if (map == null || object == null) { return false; } for (K key : map.keySet()) { V value = map.get(key); if (value.equals(object)) { return true; } } return false; }
根據key 排序
import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** * @Auther: lizhi * @Date: 2018/9/12 20:59 * @Description: 根據map Key 升序降序排列 */ public class MapSortUtil{ public static <K, V> Map<K, V> sortMapAscByKey(Map<K, V> map) { if (map == null || map.isEmpty()) return new TreeMap<>(); Map<K,V> sortMap = new TreeMap(new MapKeyComparatorAsc()); sortMap.putAll(map); return sortMap; } public static <K, V> Map<K, V> sortMapDescByKey(Map<K, V> map) { if (map == null || map.isEmpty()) return new TreeMap<>(); Map<K,V> sortMap = new TreeMap(new MapKeyComparatorDesc()); sortMap.putAll(map); return sortMap; } static class MapKeyComparatorAsc implements Comparator{ @Override public int compare(Object o1, Object o2) { int i = o1.toString().compareTo(o2.toString()); return i; } } static class MapKeyComparatorDesc implements Comparator{ @Override public int compare(Object o1, Object o2) { return o2.toString().compareTo(o1.toString()); } } }