java 8 , merge()


import java.util.HashMap;
import java.util.Map;

public class j8merge {

    public static void main(String[] args) {
         
        // java 8  , merge() 
        
        Map<String,Integer> map=new HashMap<>();
        map.put("A", 1000);
        map.put("B", 2000);
        map.put("C", 3000);
        
        // add new key value ("A",99), if key "A" exist in map then do function  "(X,Y) -> (Y+X)" ,the function return value will replace the oldvalue.
        Integer newValue1 = map.merge("A", 99, (X,Y) -> (Y+X));
        Integer newValue2 = map.merge("A", 888, (X,Y) -> Y);
        // add new key value ("D",666), if key "D" not exist in map then insert the key value to map
        Integer newValue3 = map.merge("D", 666, (X,Y) -> Y);    
        Integer newValue4 = map.merge(null, 777, (X,Y) -> Y);    
        Integer newValue5 = map.merge(null, 5555, (X,Y) -> Y);    
        
        
        for(String s:map.keySet()){
            System.out.println(s+" : "+map.get(s));
        }
        
    }
    /*

null : 5555
A : 888
B : 2000
C : 3000
D : 666


*/ }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM