首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java.util.Map API

java.util.Map API

原创
作者头像
HLee
修改2021-09-09 10:40:11
6750
修改2021-09-09 10:40:11
举报
文章被收录于专栏:房东的猫房东的猫

简介

Map集合是有Key和Value的,Collection集合是只有Value。Collection集合底层也是有Key和Value,只是隐藏起来。

Map<String, String> map = new HashMap<>();
Map<String, String>map = new LinkedHashMap<>();
Map<String, String>map = new TreeMap<>();
Map<String, String>map = new Hashtable<>();

put

描述:

V put(K key, V value)

描述:向map集合中添加指定集合的所有元素

void putAll(Map<? extends K,? extends V> m)

clear

描述:把map集合中所有的键值删除

void clear()

getOrDefault

getOrDefault(Object key, V defaultValue)
意思就是当Map集合中有这个key时,就使用这个key对应的value值,如果没有就使用默认值defaultValue

merge

这个函数有三个参数:

  • 参数一:向map里面put的键
  • 参数二:向map里面put的值
  • 参数三:如果键发生重复,如何处理值。可以是一个函数,也可以写成lambda表达式。
String k = "key";
HashMap<String, Integer> map = new HashMap<String, Integer>() {{
   put(k, 1);
}};
map.merge(k, 2, (oldVal, newVal) -> oldVal + newVal);

computeIfAbsent

描述:对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hasMap 中。

hashmap.computeIfAbsent(K key, Function remappingFunction)

参数说明:
    key - 键
    remappingFunction - 重新映射函数,用于重新计算值

返回值:如果 key 对应的 value 不存在,则使用获取 remappingFunction 重新计算后的值,并保存为该 key 的 value,否则返回 value。

例如:
public static void computeIfAbsent(){ // jdk1.8新特性哦
    HashMap<String, String> map = new HashMap();
    map.put("1","is map");
    map.put("2","contains a mapping");
    map.put("3","specified");
    map.put("4","inappropriate");
    map.computeIfAbsent("5", v -> "is exist");

    System.out.println(map.get("5"));
}

computeIfPresent

描述:对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。

hashmap.computeIfPresent(K key, BiFunction remappingFunction)

参数说明:
    key - 键
    remappingFunction - 重新映射函数,用于重新计算值

返回值:如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值。

例如:
public static void computeIfPresent() {
    // 创建一个 HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // 往HashMap中添加映射关系
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // 重新计算鞋加上10%的增值税后的价值
    int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
    System.out.println("Price of Shoes after VAT: " + shoesPrice);

    // 输出更新后的HashMap
    System.out.println("Updated HashMap: " + prices);
}

工具方法

Map遍历

Cat ououCat = new Cat ("欧欧", "雪娜瑞");
Cat yayaCat = new Cat ("亚亚", "拉布拉多");
Cat meimeiCat = new Cat ("美美", "雪娜瑞");
Cat feifeiCat = new Cat ("菲菲", "拉布拉多");

Map map=new HashMap();

map.put(ououDog.getName(),ououDog);
map.put(yayaDog.getName(),yayaDog);
map.put(meimeiDog.getName(),meimeiDog);
map.put(feifeiDog.getName(),feifeiDog);

第一种:JDK1.4 迭代器遍历(使用entrySet)
Iterator<Map.Entry<String, Dog>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Dog> entry = iterator.next();
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

第二种:迭代器遍历(使用keySet)
Set keys = map.keySet();//取出所有key的集合
Iterator iterator = keys.iterator();//获取Iterator对象
while(iterator .hasNext()){
    String key=(String)iterator .next();//取出key
    Dog dog=(Dog)dogMap.get(key);//根据key取出对应的值
}

第三种:JDK1.5 增强for循环遍历(使用entrySet)
for (Map.Entry<String, Dog> entry : map.entrySet()) {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

第四种:增强for循环遍历(使用keySet)
遍历dogMap中的键 
for (String key : map.keySet()) {
    System.out.println(key + " :" + dogMap.get(key));
}
遍历dogMap中的值 
for (Integer value : map.values()) { 
  System.out.println("Value = " + value); 
}

总结:entrySet 优于keySet,因为一次就把key和value放入了entry

第五种:JDK8 Lambda拉姆达
map.forEach((key, value) -> {
    System.out.println("key: "+ key + "  value: " + value );
});
map.forEach( (k,v)->{System.out.println(k+" "+v);} );


备注:使用 entrySet 遍历 Map 类集合 KV,而不是 keySet 方式进行遍历。
说明:keySet 其实是遍历了 2 次,一次是转为 Iterator 对象,另一次是从 hashMap 中取出 key 所对应的 value。
而 entrySet 只是遍历了一次就把 key 和 value 都放到了 entry 中,效率更高。如果是 JDK8,使用 Map.forEach 方法。

总结:

增强for循环使用方便,但性能较差,不适合处理超大量级的数据。
迭代器的遍历速度要比增强for循环快很多,是增强for循环的2倍左右。
使用entrySet遍历的速度要比keySet快很多,是keySet的1.5倍左右。

Map排序

1. HashMap排序

public class HashMap {

    public static void main(String[] args){

        Map<String, String> map = new HashMap<String, String>();
        map.put("a", "a");
        map.put("e", "e");
        map.put("d", "");
        map.put("b", "b");
        map.put("c", "c");

        //通过ArrayList构造函数把map.entrySet()转换成list
        List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        //通过比较器实现比较排序
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
                return mapping1.getKey().compareTo(mapping2.getKey());
            }
        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + " :" + mapping.getValue());
        }
    }
}

备注:HashMap是无序的

描述:按Map的键排序。使用Java 8 Stream按Map的键进行排序:

// 创建一个Map,并填入数据
Map<String, Integer> codes = new HashMap<>();
codes.put("United States", 1);
codes.put("Germany", 49);
codes.put("France", 33);
codes.put("China", 86);
codes.put("Pakistan", 92);

// 按照Map的键进行排序
Map<String, Integer> sortedMap = codes.entrySet().stream()  // 首先使用entrySet().stream() 将Map类型转换为Stream流类型。
        .sorted(Map.Entry.comparingByKey())  // 使用sorted方法排序,排序的依据是Map.Entry.comparingByKey(),也就是按照Map的键排序
        .collect(  // 用collect方法将Stream流转成LinkedHashMap
                Collectors.toMap(
                    Map.Entry::getKey, 
                    Map.Entry::getValue,
                    (oldVal, newVal) -> oldVal,
                    LinkedHashMap::new
                )
        );

// 将排序后的Map打印
sortedMap.entrySet().forEach(System.out::println);

描述:按Map的值排序

Map<String, Integer> sortedMap2 = codes.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new));

sortedMap2.entrySet().forEach(System.out::println);

2. TreeMap排序

TreeMap排序:

Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
    public int compare(String obj1, String obj2) {
        return obj2.compareTo(obj1);// 降序排序
    }
});
map.put("a", "c");
map.put("b", "b");
map.put("c", "a");
 
for (String key : map.keySet()) {
    System.out.println(key + " :" + map.get(key));
}

TreeMap排序(按value排序)

Map<String, String> map = new TreeMap<String, String>();
        map.put("a", "c");
        map.put("b", "b");
        map.put("c", "a");
 
        // 通过ArrayList构造函数把map.entrySet()转换成list
        List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        // 通过比较器实现比较排序
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
                return mapping1.getValue().compareTo(mapping2.getValue());
            }
        });
 
        for (String key : map.keySet()) {
            System.out.println(key + " :" + map.get(key));
        }
}

描述:TreeMap按键排序。大家可能都知道TreeMap内的元素是有顺序的,所以利用TreeMap排序也是可取的一种方法。您需要做的就是创建一个TreeMap对象,并将数据从HashMapput到TreeMap中,非常简单:

// 将 `HashMap` 转为 `TreeMap`
Map<String, Integer> sorted = new TreeMap<>(codes);

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • put
  • clear
  • getOrDefault
  • merge
  • computeIfAbsent
  • computeIfPresent
  • 工具方法
    • Map遍历
      • Map排序
        • 1. HashMap排序
        • 2. TreeMap排序
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档