top of page
Search

Java 8 - Map replaceAll and compute

  • schick09
  • Aug 12, 2024
  • 1 min read

Java 8 introduced several improvements to collections. We are going to discuss two of them today - the Map class replaceAll and compute methods.


default void replaceAll(BiFunction)

This method can be used to replace all of the values in a map with the results of the function provided.


In the following example, we will use replaceAll to double all of the Integer values in a given HashMap.


private static void replaceAll (){
        Map<String,Integer> doubler = new HashMap<>();
        doubler.put("one",1);
        doubler.put("two",2);
        doubler.put("three",3);
        doubler.put("four",4);
        doubler.put("five",5);
        System.out.println("HashMap1: "
                + doubler.toString());
        doubler.replaceAll((key,value) -> value * 2);
        System.out.println("HashMap2: "
                + doubler.toString());
    }


compute(Key, BiFunction)

This method was also introduced in Java 8. It replaces the value for of given key in the Map with the computed value returned by the function.


If the function returns null, then the key is removed from the Map.


Here is an example of using compute to concatenate text on the String value in the Map:



    private static void compute(){
        Map<String, String> map = new HashMap<>();
        map.put("Province", "New Brunswick");
        map.put("Country", "Canada");
        System.out.println("Map: " + map);
        map.compute("Province", (key, val)
                -> val.concat(" - Maritime Province"));
        map.compute("Country", (key, val)
                -> val.concat(" - North America"));
        System.out.println("New Map: " + map);
    }

Here's a link to our GitHub location to access an example of using Map's replaceAll and compute operations: https://github.com/daveschickconsulting/java_8_examples/tree/main/src/funwithnewmapfeatures



ree





 
 
 

Comments


Dave Schick Consulting

©2023 by Dave Schick Consulting. Proudly created with Wix.com

bottom of page