• java成神之——集合框架之Maps,Hashtable


    集合

    Maps

    HashMap

    Map<KeyType, ValueType> myMap = new HashMap<KeyType, ValueType>();
    myMap.put("key1", 1);
    myMap.get("key1");
    map.replace("key1",2); 
    map.remove("key1",2); 
    myMap.containsKey(varKey);
    myMap.containsValue(varValue);
    map.replaceAll((key,value)->value+1);  // 遍历
    map.putIfAbsent("kelly", 50);  // 不重复才添加
    map.computeIfAbsent("d", k -> map.get("a"));  // 键没重复,添加
    map.computeIfPresent("d", k -> map.get("a")); // 键出现,修改键值
    map.compute("peter", (k,v)->v+50);
    map.containsKey("one");
    map.clear();
    
    
    // 如果"kelly"不存在则,直接添加键值对 kelly:50
    // 如果"kelly"存在,并且action计算的值不为null,则使用50替换原来kelly的值
    // 如果"kelly"存在,并且action计算的值为null,则直接删除"kelly"
    map.merge("kelly", 50 , (k,v)->map.get("john")+10);
    

    创建和初始化map

    第一种
    
        Map map = new HashMap();
    
    第二种
    
        Map<String, Object> map = new HashMap<>();
    
    第三种
    
        Map<String, Object> map = new HashMap<String, Object>(){{
            put("name", "A");
            put("address", "Malviya-Nagar");
            put("city", "Jaipur");
        }};
    
    第四种
    
        Map<String, Object> map = new TreeMap<String, Object>();
    
    第五种
    
        Map<String, String> map = Arrays.stream(new String[][] {
            { "name", "A" },
            { "address", "Malviya-Nagar" },
            { "city", "jaipur" },
        }).collect(Collectors.toMap(m -> m[0], m -> m[1]));
    
    第六种
    
        Map<String, String> singletonMap = Collections.singletonMap("key", "value");
    

    遍历方式

    Maps 存放键值对,不能包含重复的键
    
    Map<String, Integer> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 2);
    map.put("c", 3);
    
    第一种
        Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        while (it.hasNext()) {
            Map.Entry<String, Integer> pair = it.next();
            sj.add("{" + pair.getKey() + ": "+ pair.getValue() + "}");
        } // [{a: 1}, {b: 2}, {c: 3}]
    
    第二种
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        for (Map.Entry<String, Integer> pair : map.entrySet()) {
            sj.add("{" + pair.getKey() + ": "+ pair.getValue() + "}");
        }
    
    第三种
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        map.forEach((k, v) -> sj.add("{" + k + ": "+ v + "}"));
    
    第四种
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        for (String key : map.keySet()) {
            sj.add("{" + key + ": "+ map.get(key) + "}");
        }
    
    第五种
        Iterator<String> it = map.keySet().iterator();
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        while (it.hasNext()) {
            String key = it.next();
            sj.add("{" + key + ": "+ map.get(key) + "}");
        }
    
    第六种
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        for (Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
            Map.Entry<String, Integer> entry = entries.next();
            sj.add("{" + entry.getKey() + ": "+ entry.getValue() + "}");
        }
    
    第七种
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        map.entrySet().stream().forEach(e -> sj.add("{" + e.getKey() + ": "+ e.getValue() + "}"));
    
    第八种
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        map.entrySet().stream().parallel().forEach(e -> sj.add("{" + e.getKey() + ": "+ e.getValue() + "}")); 
    
    性能排序 3 > 6 > 1 > 2 > 7 > 4 > 5 > 8
    

    LinkedHashMap

    保留插入顺序,不允许重复键
    
    LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>();
    

    WeakHashMap

    Map weakHashMap = new WeakHashMap(); // gc会自动删除弱引用键值对
    

    TreeMap

    TreeMap tm = new TreeMap(); // 自动根据键升序排序
    

    线程锁

    TreeMap和TreeSet都是线程不安全的,所以开发多线程程序需要上锁
    
    方式一
    
        SortedSet<Integer> set = Collections.synchronizedSortedSet(new TreeSet<Integer>());
        SortedMap<Integer,String> map = Collections.synchronizedSortedMap(new TreeMap<Integer,String>());
    方式二
    
        synchronized (set) {
            set.add(4);
        }
    方式三
    
        TreeSet<Integer> set = new TreeSet<>();
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        lock.writeLock().lock();
        set.add(4);
        lock.writeLock().unlock();
    

    Hashtable

    存储唯一值,并且线程安全
    
    Hashtable<Integer, String> map = new Hashtable<Integer, String>(); 
    map.put(1,"ONE");
    

    结语

    本文章是java成神的系列文章之一
    
    如果你想知道,但是本文没有的,请下方留言
    
    我会第一时间总结出来并发布填充到本文
    
  • 相关阅读:
    图床
    MarkDown认识与入门
    IIS Express
    HTML中的英文缩写标记、属性
    AI-->从新建文档开始说起,串联相关色彩知识
    微软相关软件、操作系统常用下载方法(附离线方式)
    SubLime3 Emmet插件终极教程
    sublime text 3 扩展插件SideBarEnhancements用法教程
    几款前端开发工具比较
    关于VUE项目中报Error: Avoided redundant navigation to current location: 的错
  • 原文地址:https://www.cnblogs.com/ye-hcj/p/9724438.html
Copyright © 2020-2023  润新知