如何使用value打印hashmap的key
我可以使用键打印值,但无法使用其值打印键。
源代码
public class test {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number of element to insert in map:");
int num = sc.nextInt();
sc.nextLine();
for (int i = 0; i < num; i++) {
System.out.print("Enter a Key:");
int num1 = sc.nextInt();
sc.nextLine();
System.out.print("Enter a value:");
String str1 = sc.nextLine();
hashMap.put(num1, str1);
}
System.out.println(hashMap);
System.out.println(hashMap.get(1));
sc.close();
}
}
程序输出
Enter a number of element to insert in map:2
Enter a Key:1
Enter a value:a
Enter a Key:2
Enter a value:b
{1=a, 2=b}
a
I can print the value using key, but I can't able to print the key using its value.
Source code
public class test {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number of element to insert in map:");
int num = sc.nextInt();
sc.nextLine();
for (int i = 0; i < num; i++) {
System.out.print("Enter a Key:");
int num1 = sc.nextInt();
sc.nextLine();
System.out.print("Enter a value:");
String str1 = sc.nextLine();
hashMap.put(num1, str1);
}
System.out.println(hashMap);
System.out.println(hashMap.get(1));
sc.close();
}
}
Program Output
Enter a number of element to insert in map:2
Enter a Key:1
Enter a value:a
Enter a Key:2
Enter a value:b
{1=a, 2=b}
a
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
例如,您想使用Value ABC查找密钥:
For example, you want to find key using value abc: