Merge () the source

  • The Map interface default function #
private static void test_One(a) {
    HashMap<String, Integer> prices = new HashMap<>();
    prices.put("Shoes".100);
    prices.put("Bag".230);
    prices.put("Pant".330);

    System.out.println("prices : " + prices);
    Integer shirt = prices.merge("shirt".90.new BiFunction<Integer, Integer, Integer>() {
        @Override
        public Integer apply(Integer integer, Integer integer2) {
            returninteger + integer2; }}); System.out.println(" shirt : " + shirt);
    System.out.println("After update prices:" + prices);
}
Copy the code
  • Print the result
  1. prices : {Pant=330, Bag=230, Shoes=100}
  2. shirt : 90
  3. Prices: {Pant= Pant, shirt= 50, Bag= 50, Shoes= 50}
  • BiFunction#apply does nothing when inserting a key or value that does not exist in a map. BiFunction#apply does nothing when inserting a key or value that does not exist

Measured again

  • Merge existing keys in the map
private static void  test_two (a) {
   HashMap<String, Integer> prices = new HashMap<>();
   prices.put("Shoes".100);
   prices.put("Bag".230);
   prices.put("Pant".330);

   System.out.println(" old prices : " + prices);

   // Notice that "Pant" already exists in map;
   Integer newPant = prices.merge("Pant".90.new BiFunction<Integer, Integer, Integer>() {
       @Override
       public Integer apply(Integer integer, Integer integer2) {
            // Integer is the value put in before: 330; Integer2 is the value of merge,
           System.out.println(" integer : "+integer+", integer2 : "+integer2);
           returninteger + integer2; }}); System.out.println(" newPant : " + newPant);
   System.out.println("Updated prices:" + prices);
}
Copy the code
  • Print the result
  1. old prices : {Pant=330, Bag=230, Shoes=100}
  2. integer : 330, integer2 : 90
  3. newPant : 420
  4. Pant= Pant, Bag= Pant, Shoes= 50}
  • Pant’s final value is integer + integer2 = 330+90= 420. The apply() function does custom operations on integer and integer1, such as addition, subtraction, multiplication and division….

The last

  • Thanks, newbie. Great site
  • Rare nature much strange, it is small scene….
  • Thank you, LeetCode 169. If it were not for the brush algorithm, I would not know that map has this operation.