package com.map;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
public class AddMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Double> AMap = new HashMap<String,Double>(){{
put("A",1.0);
put("B",2.0);
put("C",-3.0);
}};
Map<String,Double> BMap = new HashMap<String,Double>(){{
put("B",-2.0);
put("C",3.0);
put("D",6.0);
}};
Map<String,Double> CMap = addWeight(AMap,BMap);
for(String s : CMap.keySet())
{
System.out.println(s + " = " + CMap.get(s));
}
}
public static Map<String,Double> addWeight(Map<String,Double> goldMap,Map<String,Double> preMap)
{
Map<String,Double> addMap = new HashMap<String,Double>();
for(String s : preMap.keySet())
{
if(goldMap.containsKey(s))
{
addMap.put(s, (goldMap.get(s) + preMap.get(s)));
} else
{
addMap.put(s, preMap.get(s));
}
}
for(String str : goldMap.keySet())
{
if(!preMap.containsKey(str))
{
addMap.put(str, goldMap.get(str));
}
}
//删除值为空的项
//集合类的都不能在循环的时候删除,因为删除元素后集合发生改变继而不能循环了
//这种删除方式以后不要再用了,严重出错
/*for(String key : cutMap.keySet())
{
Double value = cutMap.get(key);
if(value == 0.0)
{
cutMap.remove(key);
}
}*/
Set mapset = addMap.entrySet();
Iterator iterator = mapset.iterator();
while(iterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry)iterator.next();
Double value =(Double)mapEntry.getValue();
if(value == 0.0)
{
iterator.remove();
}
}
return addMap;
}
/**
* 两个Map相减
* @param goldMap
* @param preMap
* @return
*/
public static Map<String,Double> cutWeight(Map<String,Double> goldMap,Map<String,Double> preMap)
{
Map<String,Double> cutMap = new HashMap<String,Double>();
for(String s : preMap.keySet())
{
if(goldMap.containsKey(s))
{
cutMap.put(s, (goldMap.get(s)-preMap.get(s)));
} else
{
cutMap.put(s, -(preMap.get(s)));
}
}
for(String str : goldMap.keySet())
{
if(!preMap.containsKey(str))
{
cutMap.put(str, goldMap.get(str));
}
}
//删除值为空的项
Iterator iterator = cutMap.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry)iterator.next();
Double value =(Double)mapEntry.getValue();
if(value == 0.0)
{
iterator.remove();
}
}
return cutMap;
}
}
Java中两个Map的加减
最新推荐文章于 2024-09-02 20:46:34 发布