I want to make the method removeValue( "a", "x").
It must delete all keys and values between the letters. For example:
{1=a,2=b,3=c,5=x} ->> {1=a,5=x}
I tried with equals and iterator but I don't know how to write it.
public class CleanMapVal {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "w");
map.put("5", "x");
System.out.println( map );
for (Iterator<String> it = map.keySet().iterator(); it.hasNext();)
if ("2".equals(it.next()))
it.remove();
System.out.println(map);
}
public static <K, V> void removeValue(Map<K, V> map) throws Exception {
Map<K, V> tmp = new HashMap<K, V>();
for (Iterator<K> it = map.keySet().iterator(); it.hasNext();) {
K key = it.next();
V val = map.get(key);
if (!tmp.containsValue(val)) {
tmp.put(key, val);
}
}
map.clear();
for (Iterator<K> it = tmp.keySet().iterator(); it.hasNext();) {
K key = it.next();
map.put((K) tmp.get(key), (V) key);
}
}
}
Mapdoesn't guarantee the ordering of its entries; so there is no such thing as "keys between a and x" to begin with. Of course, you could also use aLinkedHashMapbut my suspiscion is that this is a XY problem to begin with.{a=1, b=2, c=3, d=2, e=1}and you invokeremoveValue( "1", "3"). Should result be{a=1, c=3, d=2, e=1}or{a=1, c=3, e=1}or maybe something else?