[英]How do I store the key and value into hashmap and print it out accordingly?
[英]Hashmap - Key: String, Value: Boolean. How do I test the value within an if statement?
/ public void getFinishedBooks(HashMap<String, Boolean> library) {
if (library.size() < 1) {
System.out.println("No books in Library");
} else {
for (String books : library.keySet()) {
**if (library.value == true) {**
如果数据类型为Boolean的Hashmap“值”等于try,我希望运行底部的IF语句。 我已经尝试过.get(),但是没有用。
使用下面的代码它将起作用
for (String books : library.keySet()) {
if(books != null){
Boolean libValue = library.get(books );
if (libValuetrue) {
//added as per your code
}
}
}
无需获取键集,而是获取条目集-这意味着您可以遍历键/值对,而不必再次查找每个键。 例如,要打印具有true
值的所有书籍:
for (Map.Entry<String, Boolean> entry : map.entrySet()) {
if (entry.getValue()) {
System.out.println(entry.getKey());
}
}
或者如果您的值可能为null,则处理null:
for (Map.Entry<String, Boolean> entry : map.entrySet()) {
if (TRUE.equals(entry.getValue()) {
System.out.println(entry.getKey());
}
}
if (library.isEmpty()) {
System.out.println("No books in Library");
} else {
for (String books : library.keySet()) {
if (library.get(books)) {
或者
for (Entry<String, Boolean> entry : library.entrySet()) {
if (entry.getValue()) {
但是,使用Set<String>
会更理想。
Set<String> library = new HashSet<>();
if (library.contains(...))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.