Reputation:
I have a String exp, which I have to compare with the mapsList.
String exp = "nodeId=1&&name=Router||level=1";
List mapList = new ArrayList();
Map map = new HashMap();
map.put("nodeId","1");
map.put("name","Router");
map.put("level", "1");
Map map1 = new HashMap();
map1.put("nodeId","2");
map1.put("name","Router");
map1.put("level","2");
Map map2 = new HashMap();
map2.put("nodeId","3");
map2.put("name","Router");
map2.put("level","3");
mapList.add(map);
mapList.add(map1);
mapList.add(map2);
I take the exp and split into an array.
String delims = "[\\&&\\||\\=]+";
String[] token = exp.split(delims);
Then I divide the array into two smaller sub arrays. One for Keys and the other for values. After which I compare ...
if(map.keySet().contains(a1[0]) && map.keySet().contains(a1[1]) || map.keySet().contains(a1[2])){
if(map.values().contains(a2[0]) && map.values().contains(a2[1]) || map.values().contains(a2[2])){
System.out.println("Match\tMapKeys: "+map.keySet()+" Values: "+map.values());
}else{
System.out.println("No Match\t");
}
}
So my problem is I can do this for each map, but can't figure out how to implement it with iterator.
Can some1 push me in the right direction?
Thanks.
Upvotes: 0
Views: 123
Reputation: 9908
You really, really want to define an object to hold your data, instead of using HashMap
s.
class Node {
private int id;
private String name;
private int level;
public Node(int id, String name, int level) {
this.id = id;
this.name = name;
this.level = level;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getLevel() {
return level;
}
}
now you populate the list like this
List<Node> nodeList = new ArrayList<Node>();
nodeList.add(new Node(1, "Router", 1));
nodeList.add(new Node(2, "Router", 2));
nodeList.add(new Node(3, "Router", 3));
and you could look for your match like this
String exp = "nodeId=1&&name=Router||level=1";
String delims = "[\\&&\\||\\=]+";
String[] token = exp.split(delims);
int id = Integer.parseInt(token[1]);
String name = token[3];
int level = Integer.parseInt(token[5]);
boolean match = false;
for (Node node : nodeList) {
if (node.getId() == id && node.getName().equals(name)
&& node.getLevel() == level) {
System.out.println("Match found: " + node);
match = true;
}
}
if (!match) {
System.out.println("No match");
}
which gives me the following output
Match found: Node@1391f61c
and the next step is to implement toString
.
You should check out http://docs.oracle.com/javase/tutorial/java/concepts/ as it introduces objects and why they are useful.
Upvotes: 2