Advertisement
ivana_andreevska

Compute If Absent metod

Aug 23rd, 2022
1,000
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. package POMOS;
  2.  
  3. import java.util.HashMap;
  4.  
  5. public class HashMapPomos {
  6.     public static void main(String[] args) {
  7.         HashMap<Integer,String> map=new HashMap<>();
  8.         map.put(10,"Ivana");
  9.         map.put(20,"Ivona");
  10.         map.put(30,"Angela");
  11.  
  12.         //System.out.println("HashMap:\n"+map.toString());
  13.  
  14.  
  15.         //provide value for new key which is absent with computeIfAbsent
  16.         map.computeIfAbsent(40,value->"Sandra");
  17.  
  18.         //this will not affect anything because key 10 is present
  19.         map.computeIfAbsent(10, value->"Ivana");
  20.  
  21.         //System.out.println("New HashMap:\n" +map.toString());
  22.  
  23.         HashMap<String,Integer> prices=new HashMap<>();
  24.         prices.put("Shoes",200);
  25.         prices.put("Bag",100);
  26.         prices.put("Pants",300);
  27.  
  28.         System.out.println("Prices"+ prices.toString());
  29.         System.out.println();
  30.  
  31.         //compute if absent value of shirt
  32.         prices.computeIfAbsent("Shirt",value->500);
  33.  
  34.         System.out.println("New prices"+prices.toString());
  35.         System.out.println();
  36.  
  37.     }
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement