I was working on a program to validate that a map contains some set of values or not. Map
API is having one method called as map.containsValue(string)
. But, this method verify complete String as value.
import java.util.HashMap;
import java.util.Map;
public class TestMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(6, "P_T");
map.put(7, "P_Q_T");
map.put(8, "T");
map.put(9, "A");
map.put(10, "B");
map.put(11, "P_A");
map.put(1, "P_1");
map.put(2, "Q");
map.put(3, "P_Q");
map.put(4, "Q_T");
map.put(5, "T");
System.out.println("Map is = "+map);
System.out.println("Result is = " + map.containsValue("P"));
}
}
Above program will return output as :
Map is = {1=P_1, 2=Q, 3=P_Q, 4=Q_T, 5=T, 6=P_T, 7=P_Q_T, 8=T, 9=A, 10=B, 11=P_A}
Result is = false
My requirement is that Result
should be true as, Map contains keys 1, 3, 6, 7, 11, which contains char P
as value.
I have a solution, that i could use loop to verify each value and then find indexOf
each value for P
char.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(6, "P_T");
map.put(7, "P_Q_T");
map.put(8, "T");
map.put(9, "A");
map.put(10, "B");
map.put(11, "P_A");
map.put(1, "P_1");
map.put(2, "Q");
map.put(3, "P_Q");
map.put(4, "Q_T");
map.put(5, "T");
System.out.println("Map is = " + map);
System.out.println("Result is = " + map.containsValue("P"));
System.out.println("Result from loop is = " + verifyMap(map));
}
private static boolean verifyMap(Map<Integer, String> map) {
// TODO Auto-generated method stub
Set<Integer> set = map.keySet();
Iterator<Integer> itr = set.iterator();
while (itr.hasNext()) {
Integer integer = (Integer) itr.next();
String str = map.get(integer);
if (str.indexOf("P") >= 0)
return true;
}
return false;
}
}
I have evaluated string
with indexOf
method instead of contains
, which is marginally faster .
This return the desired result as:
Result from loop is = true
But, I just want to know, is there any other way to verify same?