Question

Below is data from 2 linkedHashMaps:

valueMap:   { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}

What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.

Here is my attempt so far:

for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
   double doubleOfValueMap = entryNumber.getValue();
   for(String StringFromValueMap: strArray){
      for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){          
         String StringFromFormulaMap = entryFormula.toString();
         if(StringFromFormulaMap.contains(StringFromValueMap)){
           entryFormula.setValue(doubleOfValueMap);
         }
      }
   }
}

The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.

Let me know if you have any ideas as to what I can do?

Was it helpful?

Solution

This is quite simple:

formulaMap.putAll(valueMap);

If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:

final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);

Edit due to comment It appears the problem was not at all what I thought, so here goes:

// The result map
for (final String key: formulaMap.keySet()) {
    map.put(formulaMap.get(key), valueMap.get(key));

// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);

OTHER TIPS

for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){          
  formulaMap.put(valueFormula.getKey(), valueFormula.value());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top