![](/img/trans.png)
[英]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.