MapInverter { public static Map<String, String> createInvertedTreeMap(Map map) { final TreeMap<String, String> swappedMap = new TreeMap<String, String>(); final Set<Map.Entry> set = map.entrySet(); for (Map.Entry entry : set) { final String newKey = (String) entry.getValue(); if (swappedMap.containsKey(newKey)) { throw new IllegalArgumentException("The map must contain only unique values"); } swappedMap.put(newKey, (String) entry.getKey()); } return swappedMap; }  static Map<String, String> createInvertedTreeMap(Map map);  }
@Test public void testInverting() { final Map<String, String> map = new HashMap<String, String>(); map.put("Key1", "Value1"); map.put("Key2", "Value2"); map.put("Key3", "Value3"); final Map<String, String> swappedMap = MapInverter.createInvertedTreeMap(map); assertNotNull(swappedMap); assertEquals(3, swappedMap.size()); assertEquals("Key1", swappedMap.get("Value1")); assertEquals("Key2", swappedMap.get("Value2")); assertEquals("Key3", swappedMap.get("Value3")); }
@Test public void testIllegalArgumentException_IfMapNotContainsOnlyUniqueValues() { final Map<String, String> map = new HashMap<String, String>(); map.put("Key1", "Value1"); map.put("Key2", "Value"); map.put("Key3", "Value"); try { MapInverter.createInvertedTreeMap(map); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } catch (Throwable e) { fail("IllegalArgumentException expected"); } }