Java 树映射逻辑中嵌套的If-else循环
我在Java 树映射逻辑中嵌套的If-else循环,java,loops,if-statement,treemap,Java,Loops,If Statement,Treemap,我在树状图中输入值,如下所示: if (hdr.getName().equalsIgnoreCase("Ip4")) { map.put(1, f); } else if (hdr.getName().equalsIgnoreCase("ethernet")) { map.put(2, f); } else if (hdr.getName().equalsIgnoreCase("tcp")) { map.put(3, f); } else if (hdr
树状图中输入值,如下所示:
if (hdr.getName().equalsIgnoreCase("Ip4")) {
map.put(1, f);
} else if (hdr.getName().equalsIgnoreCase("ethernet")) {
map.put(2, f);
} else if (hdr.getName().equalsIgnoreCase("tcp")) {
map.put(3, f);
} else
if (hdr.getName().equalsIgnoreCase("udp")) {
map.put(4, f);
}
我正在尝试使用以下方法检索它:
Iterator < Map.Entry < Integer, Field >> entries = map2.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry < Integer, Field > entry = entries.next();
if ((entry.getKey() == 1)) {
stringBuilder.append(entry.getValue().getSource());
stringBuilder.append(",");
stringBuilder.append(entry.getValue().getDestination());
} else if ((entry.getKey() == 2)) {
stringBuilder.append(entry.getValue().getSource());
stringBuilder.append(",");
stringBuilder.append(entry.getValue().getDestination());
} else if ((entry.getKey() == 3)) {
stringBuilder.append(entry.getValue().getSource());
stringBuilder.append(",");
stringBuilder.append(entry.getValue().getDestination());
} else if ((entry.getKey() == 4)) {
stringBuilder.append(entry.getValue().getSource());
stringBuilder.append(",");
stringBuilder.append(entry.getValue().getDestination());
}
}
比如说
If key 1 contains 12,13
If key 2 is not present ,,
If key 3 contains 10,11
If key 4 contains 14,15
因此,期望的输出应该是
12,13,,10,11,14,15
请帮助我的逻辑,因为我打破了我的头在这个
谢谢你的提示David,我用
for (int i=1 ; i<=map2.size()+1; i++){
if(map2.containsKey(i))
{
//appendString(map2.get(i));
stringBuilder.append(map2.get(i).getSource());
stringBuilder.append(",");
stringBuilder.append(map2.get(i).getDestination());
}
else{
stringBuilder.append(",,");
}
}
for(int i=1;iyou正在对该映射中存在的条目进行迭代,因此如果2不在映射中,则不会为其打印任何内容。难道您不能让某个变量从1循环到4,然后使用get
查看映射中的内容吗?@Eran,如果2不存在,我希望(,)要打印,也就是说,在任何时候1、2、3、4或其任何组合都不会出现,所以我必须检查值是否存在任何键。David,我将检查这一点并更新我建议您测试3和4存在,但1和2不存在的情况。您可能无法得到预期的结果。
for (int i=1 ; i<=map2.size()+1; i++){
if(map2.containsKey(i))
{
//appendString(map2.get(i));
stringBuilder.append(map2.get(i).getSource());
stringBuilder.append(",");
stringBuilder.append(map2.get(i).getDestination());
}
else{
stringBuilder.append(",,");
}
}