我有HashMap,其中key是bird specie,value是感知数量。这是我的代码:
public class Program {
public static void main(String[] args) {
HashMap<String, Integer> species = new HashMap<>();
Scanner reader = new Scanner(System.in);
species.put("hawk (buteo jamaicensis)", 2);
species.put("eagle (aquila chrysaetos)", 4);
species.put("sparrow (passeridae)", 5);
System.out.println("What specie?"); //output "chicken"
String specie = reader.nextLine();
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
if (entry.getKey().contains(specie)) {
System.out.println(entry.getKey()+" : "+entry.getValue()+" perceptions");
} else {
System.out.println("Not in database!");
}
}
}
}
如何检查hashmap中是否存在硬币?例如,如果物种输出是“鸡”并且它不在数据库中,那么程序应该打印“不在数据库中!”。现在输出是:
Not in database!
Not in database!
Not in database!
我的目标输出是:
Not in database!
答案 0 :(得分:1)
为此使用布尔标志:
boolean found = false;
for (HashMap.Entry<String, Integer> entry: species.entrySet()) {
if (entry.getKey().contains(specie)) {
System.out.println(entry.getKey()+" : "+entry.getValue()+" perceptions");
found = true;
}
} //Loop ends
if (!found) {
System.out.println("Not in database!");
}
答案 1 :(得分:0)
您也可以使用Java 8 Streams :(虽然我可能只推荐使用for循环)
Optional<Map.Entry<String, Integer>> match =
species.entrySet().stream().filter(entry -> entry.getKey().contains(specie)).findAny();
if (match.isPresent())
System.out.println(match.get().getKey()+" : "+match.get().getValue()+" perceptions");
else
System.out.println("Not in database!");
.stream
将条目集转换为流
.filter
除了我们正在寻找的元素之外的所有元素
.findAny
返回一个元素(如果存在)。
虽然,如果你循环浏览Map以找到你正在寻找的东西,那么这会破坏Map的目的,你可能想要选择一些自定义类的List,将String拆分为2然后让密钥成为常用英文名称(作为评论中推荐的laune)或使用更复杂的数据结构,允许有效的子字符串查找,如suffix tree。
答案 2 :(得分:0)
我认为溪流对此来说太过分了。
if(species.containsKey(selectedSpecie)) {
return species.get(selectedSpecie);
} else {
throw new IllegalStateException("Not in database!");
}