In Java 8 how do I transform a Map to another Map using a lambda?

前端 未结 7 1121
悲&欢浪女
悲&欢浪女 2020-12-02 14:01

I\'ve just started looking at Java 8 and to try out lambdas I thought I\'d try to rewrite a very simple thing I wrote recently. I need to turn a Map of String to Column int

相关标签:
7条回答
  • 2020-12-02 14:44
    Map<String, Integer> map = new HashMap<>();
    map.put("test1", 1);
    map.put("test2", 2);
    
    Map<String, Integer> map2 = new HashMap<>();
    map.forEach(map2::put);
    
    System.out.println("map: " + map);
    System.out.println("map2: " + map2);
    // Output:
    // map:  {test2=2, test1=1}
    // map2: {test2=2, test1=1}
    

    You can use the forEach method to do what you want.

    What you're doing there is:

    map.forEach(new BiConsumer<String, Integer>() {
        @Override
        public void accept(String s, Integer integer) {
            map2.put(s, integer);     
        }
    });
    

    Which we can simplify into a lambda:

    map.forEach((s, integer) ->  map2.put(s, integer));
    

    And because we're just calling an existing method we can use a method reference, which gives us:

    map.forEach(map2::put);
    
    0 讨论(0)
提交回复
热议问题