CodeGym /Java 博客 /随机的 /如何在 Java 中使用 entrySet() 方法
John Squirrels
第 41 级
San Francisco

如何在 Java 中使用 entrySet() 方法

已在 随机的 群组中发布

Java 中的 entrySet() 方法是什么?

HashMap类在 Java提供了java.util.HashMap.entrySet()方法。它用于创建并返回 HashMap 中已经存在的相同元素的“集合它可以与循环一起使用以迭代HashMap的所有条目。

方法头

下面给出了entrySet()方法的标头。它返回包含键值对的所有条目的集合视图。要在我们的代码中使用它,我们需要导入java.util.HashMap包。

public Set<Map.Entry<key, value>> entrySet()

参数

entrySet ()方法不接受任何参数。

返回类型

java.util.HashMap.entrySet ()方法返回类集的一个实例。

例子


import java.util.HashMap;

public class Driver1 {

	public static void main(String[] args) {

		// declare a custom hash map
		HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

		// add data to the hash map
		hashMap.put(1, "Monday");
		hashMap.put(2, "Tuesday");
		hashMap.put(3, "Wednesday");
		hashMap.put(4, "Thursday");
		hashMap.put(5, "Friday");
		hashMap.put(6, "Saturday");
		hashMap.put(7, "Sunday");

		// print the original hash map
		System.out.println("Original HashMap: " + hashMap + '\n');
		// print the entrySet of the hash map
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

		// Try adding null value in the hash map
		hashMap.put(0, null);
		System.out.println("hashMap.put(0, null)");
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

		// Try adding null key and value pair to the hash map
		hashMap.put(null, null);
		System.out.println("hashMap.put(null, null)");
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

		// Try adding a null character as a value in the hash map 
		hashMap.put(null, "\0");
		System.out.println("hashMap.put(null, \"\\0\")");
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

	}
}

输出

原始HashMap: {1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday} HashMap.entrySet(): [1=Monday, 2=Tuesday, 3=Wednesday , 4=星期四, 5=星期五, 6=星期六, 7=星期日] hashMap.put(0, null) HashMap.entrySet(): [0=null, 1=星期一, 2=星期二, 3=星期三, 4=星期四, 5=星期五, 6=星期六, 7=星期日] hashMap.put(null, null) HashMap.entrySet(): [0=null, null=null, 1=星期一, 2=星期二, 3=星期三, 4 =星期四, 5=星期五, 6=星期六, 7=星期日] hashMap.put(null, "\0") HashMap.entrySet(): [0=null, null= , 1=星期一, 2=星期二, 3=星期三,4=星期四,5=星期五,6=星期六,7=星期日]

解释

在上面的代码片段中,我们首先导入了java.util.HashMap包。它允许我们使用HashMapentrySet()方法。然后我们创建一个hashMap ,它是HashMap类的对象。我们的hashMap包含字符串作为值。键是整数。然后我们填充hashMap。总共有七个条目。然后我们使用setEntry()方法返回一个集合视图,然后在控制台上打印。

结论

这是 Java HashMap entrySet()方法的简单实现。希望您在阅读完这篇文章后熟悉该方法的使用。一如既往,我们鼓励您一遍又一遍地练习以精通它。到那时,继续练习并继续成长!
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION