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


*/ }

 

posted on 2017-08-22 15:55  rojas  阅读(5018)  评论(0编辑  收藏  举报