在Java中獲取HashMap鍵的集合檢視
要在Java中獲取HashMap鍵的集合檢視,可以使用名為“keySet()”的內建方法。這裡,HashMap是一個用於實現Map介面的類。它以鍵值對的形式儲存元素。鍵是一個用於獲取和接收與其關聯的值的物件。它可以訪問Map介面的所有方法,本身沒有任何額外的方法。不允許重複的值,儘管我們可以儲存空值和鍵。
Java程式:獲取HashMap鍵的集合檢視
keySet() 方法
它與HashMap集合的例項一起使用。此方法不需要任何引數,並返回指定集合中所有可用鍵的集合檢視。
語法
HashMapObject.keySet()
要使用HashMap集合,我們需要使用以下語法建立其例項。
語法
HashMap<TypeOfKey, TypeOfValue> nameOfMap = new HashMap<>();
方法
第一步是匯入“java.util”包。這將啟用HashMap類的使用。
建立HashMap集合的例項。這裡,鍵將是String型別,值將是Integer型別。
現在,使用內建方法“put()”向其中新增一些元素。
使用for-each迴圈和“keySet()”方法迭代鍵並列印它們。
示例1
以下示例說明了使用for-each迴圈的“keySet()”方法。
import java.util.*;
public class Maps {
public static void main(String[] args) {
HashMap<String, Integer> workers = new HashMap<>();
// Adding elements in the workers map
workers.put("Vaibhav", 4000);
workers.put("Ansh", 3000);
workers.put("Vivek", 1500);
workers.put("Aman", 2000);
workers.put("Tapas", 2500);
// printing all the keys of workers map
System.out.println("List of keys in the map: ");
for (String unKey : workers.keySet()) { // iterate through keys
System.out.println("Name: " + unKey);
}
}
}
輸出
List of keys in the map: Name: Vivek Name: Aman Name: Tapas Name: Vaibhav Name: Ansh
方法
建立HashMap集合的例項。這裡,鍵和值都是Integer型別。
將鍵儲存到集合中,並使用迭代器迭代鍵集合。
現在,使用while迴圈檢查可用鍵並列印它們。
示例2
以下示例說明了使用迭代器的“keySet()”方法。
import java.util.*;
public class Maps {
public static void main(String[] args) {
HashMap<Integer, Integer> cart = new HashMap<>();
// Adding elements in the cart map
cart.put(10, 400);
cart.put(20, 300);
cart.put(30, 150);
cart.put(40, 200);
cart.put(50, 250);
// printing keys of cart map
System.out.println("List of keys in the map: ");
Set keys = cart.keySet(); // storing keys to the set
Iterator itr = keys.iterator(); // iterating through keys
while (itr.hasNext()) { // check and print keys
System.out.println("Quantity: " + itr.next());
}
}
}
輸出
List of keys in the map: Quantity: 50 Quantity: 20 Quantity: 40 Quantity: 10 Quantity: 3
示例3
在以下示例中,我們將獲得集合檢視,而無需使用for-each迴圈和迭代器。
import java.util.*;
public class Maps {
public static void main(String[] args) {
HashMap<Integer, Integer> cart = new HashMap<>();
// Adding elements in the cart map
cart.put(10, 400);
cart.put(20, 300);
cart.put(30, 150);
cart.put(40, 200);
cart.put(50, 250);
// printing keys of cart map
System.out.println("List of keys in the map: ");
Set keys = cart.keySet(); // storing keys to the set
Iterator itr = keys.iterator(); // iterating through keys
while (itr.hasNext()) { // check and print keys
System.out.println("Quantity: " + itr.next());
}
}
}
輸出
List of keys in the map: Quantity: 50 Quantity: 20 Quantity: 40 Quantity: 10 Quantity: 30
結論
HashMap類和Map介面是集合框架的一部分。集合允許將物件分組到單個單元中。在本文中,我們首先定義了HashMap類,然後討論了一些Java示例程式,以從Java HashMap中獲取集合檢視。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP