Adding a value to a list to an already existing key in Map

后端 未结 3 1712
自闭症患者
自闭症患者 2021-01-07 06:42

Evening!

I have the following Map:

HashMap myMap = new HashMap();

I then added th

3条回答
  •  佛祖请我去吃肉
    2021-01-07 06:59

    import java.util.*;
    
    class M {
        public static void main( String ... args ) {
            List l = new ArrayList<>();
            l.add("Test 1");
            l.add("Test 2");
            l.add("Test 3");
    
            Map> m = new HashMap<>();
            m.put("Tests", l );
    
            // some time later that day ... 
            m.computeIfAbsent("Tests", k -> new ArrayList<>()).add("Test 4");
            System.out.println(m);
        }
    }
    

提交回复
热议问题