把两个map中的key-value进行替换

402 阅读1分钟

项目当中涉及到把两个map中的key-value进行替换:

public class Test {
	private static Map<Object, Object> sourceMap = new HashMap<Object, Object>();
	private static Map<Object, Object> targetmap = new HashMap<Object, Object>();
	static {
		sourceMap.put("source", "s");
		targetmap.put("target", "t");
	}
	public static void main(String[] args) {
		for (Entry<Object, Object> map : sourceMap.entrySet()) {
			Object sourceKey = map.getKey();
			Object sourceValue = map.getValue();
			Object targetKey = Test.getconventKey(targetmap);
			Object targetValue = Test.getconventValue(targetmap);
			sourceMap.remove(sourceKey);
			targetmap.remove(targetKey);
			sourceMap.put(targetKey, targetValue);
			targetmap.put(sourceKey, sourceValue);
			for (Entry<Object, Object> map1 : sourceMap.entrySet()) {
				Object sourceKey1 = map1.getKey();
				Object sourceValue1 = map1.getValue();
				System.out.println("sourceKey1=" + sourceKey1
						+ ",sourceValue1=" + sourceValue1);
			}
			// 这个打印的还是原来的结果
			System.out.println("sourceKey=" + sourceKey + ",sourceValue="
					+ sourceValue + "\ntargetKey=" + targetKey
					+ ",targatValue=" + targetValue);
		}
	}
	private static Object getconventKey(Map<Object, Object> targetmap) {
		Object key = null;
		for (Entry<Object, Object> map : targetmap.entrySet()) {
			key = map.getKey();
		}
		return key;
	}
	private static Object getconventValue(Map<Object, Object> targetmap) {
		Object value = null;
		for (Entry<Object, Object> map : targetmap.entrySet()) {
			value = map.getValue();
		}
		return value;
	}
}

参考:www.cnblogs.com/love-you-gi…