Compare values between two HashMap

1

I have two HashMap in my code

  HashMap<Long, Double> partesTrabajoIdHorasDb = new HashMap<>();//ID+horas
  HashMap<Long, Double> partesTrabajoIdHorasLocal = new HashMap<>();

The first Hashmap

  

partsTrabajoIdHorasDb

saves two values key = id and valor = horas_totales_trabajo_remoto

In the second HashMap

  

partsTrabajoIdHorasLocal

has the same format key = id and valor = horas_totales_trabajo_local

What I have to do is look for the coincidences of id between the two HashMap and once found to add both values ie in pseudocodigo:

if (TrabajoIdHorasDb.id == partesTrabajoIdHorasLocal.id)
horas totales = horas_totales_trabajo_remoto + horas_totales_trabajo_local

Can someone tell me what to do to find the id common between both HashMap and add the values for those ids?

    
asked by JoCuTo 06.03.2018 в 17:09
source

1 answer

1

If you want to obtain the keys that match between 2 HashMaps and add their values you can do it this way:

    for (Map.Entry<Long, Double> entry1 : partesTrabajoIdHorasDb.entrySet()) {
      Long key = entry1.getKey(); 

      //Compara los key si son iguales.                   
      if(partesTrabajoIdHorasLocal.containsKey(key)){

      //si son iguales obtiene los valores.
          Double value1 = entry1.getValue();
          Double value2 = partesTrabajoIdHorasLocal.get(key); 
        System.out.println ("El key es igual : " + key + " las horas totales son: " + (value1 + value2));            

      }
    }

How to iterate and find a match in key between 2 HashMap. I add a full example :

    Map<Long, Double> HashMap1 = new HashMap<>();
    HashMap1.put(1L, 12.2);
    HashMap1.put(2L, 22.1);
    HashMap1.put(3L, 14.5);
    HashMap1.put(4L, 11.9);
    HashMap1.put(5L, 34.5);
    HashMap1.put(6L, 24.7);

    Map<Long, Double> HashMap2 = new HashMap<>();
    HashMap2.put(10L, 12.1);        
    HashMap2.put(11L, 14.4);
    HashMap2.put(2L, 18.9);
    HashMap2.put(14L, 19.5);
    HashMap2.put(29L, 12.5);


    for (Map.Entry<Long, Double> entry1 : HashMap1.entrySet()) {
      Long key = entry1.getKey();                    
      if(HashMap2.containsKey(key)){
          Double value1 = entry1.getValue();
          Double value2 = HashMap2.get(key); 
        System.out.println ("Se encontro similar key con valor : " + key + " el valor sumado es: " + (value1 + value2));            
      }
    }
    
answered by 06.03.2018 / 17:37
source