当前位置:网站首页>Four methods of traversing key value in map
Four methods of traversing key value in map
2022-07-19 11:01:00 【Java collection】
Four ways First use
keySet()Remove all key value , Then take out the corresponding value—— enhance for Loop traversalFirst use
keySet()Remove all key value , Then take out the corresponding value—— Use iterators to traverseadopt
entrySetTo getkey-value—— enhance for Loop traversaladopt
entrySetTo getkey-value—— Use iterators to traverse

Map yes java The interface ,Map.Entry yes Map An internal interface for .Map Provides some common methods , Such as keySet()、entrySet() Other methods ,keySet() Method return value is Map in key It's worth it Set aggregate ;entrySet() The return value of also returns a Set aggregate , The type of this collection is Map.Entry<K, V>.
Map.Entry yes Map An internal interface for declarations , This interface is generic , Defined as Entry<K,V>. It said Map One of the entities in ( One key-value Yes ). There are getKey(),getValue Method .
1、 structure HashMap, to hashMap Additive elements
HashMap hashMap = new HashMap();
hashMap.put(" The romance of The Three Kingdoms "," Luo Guanzhong ");
hashMap.put(" Water margin "," Shi Naian ");
hashMap.put(" Journey to the west "," Wu chengen ");
hashMap.put(" A dream of red mansions "," Cao xueqin ");2、 Method 1 : First use keySet() Remove all key value , Then take out the corresponding value—— Use iterators to traverse
2.1 Code
/*1、 First use keySet() Remove all key value , Then take out the corresponding value—— enhance for Loop traversal */
System.out.println("====1、 First use keySet() Remove all key value , Then take out the corresponding value—— enhance for Loop traversal ====");
Set keyset = hashMap.keySet();
for(Object key:keyset){
System.out.println(key+"-"+hashMap.get(key));
}2.2 Running results

3、 Method 2 : Take out all... First key, Re pass key Take out the corresponding value—— Use iterators to traverse
3.1 Code
/*2、 First use keySet() Remove all key value , Then take out the corresponding value—— Use iterators to traverse */
System.out.println("====2、 First use keySet() Remove all key value , Then take out the corresponding value—— Use iterators to traverse ====");
Iterator iterator = keyset.iterator();
while(iterator.hasNext()){
Object key = iterator.next();
System.out.println(key+"-"+hashMap.get(key));
}3.2 Running results

4、 Method 3 : adopt entrySet() get key-value value —— enhance for Loop traversal
4.1 Code
/*3、 adopt entrySet() get key-value value —— enhance for Loop traversal */
System.out.println("====3、 adopt entrySet() get key-value value —— enhance for Loop traversal ====");
Set set = hashMap.entrySet();
for(Object key:set){
Map.Entry entry = (Map.Entry) key;
System.out.println(entry.getKey()+"-"+entry.getValue());
}4.2 Running results

5、 Method four : adopt entrySet() get key-value value —— Use iterators to traverse
5.1 Code
/*4、 adopt entrySet() get key-value value —— Use iterators to traverse */
System.out.println("====4、 adopt entrySet() get key-value value —— Use iterators to traverse ====");
Set set1 = hashMap.entrySet();
Iterator iterator1 = set1.iterator();
while(iterator1.hasNext()){
Object itset = iterator1.next();
Map.Entry entry = (Map.Entry) itset;
System.out.println(entry.getKey()+"-"+entry.getValue());
}5.2 Running results
6、 Complete code
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTraverse {
public static void main(String[] args){
HashMap hashMap = new HashMap();
hashMap.put(" The romance of The Three Kingdoms "," Luo Guanzhong ");
hashMap.put(" Water margin "," Shi Naian ");
hashMap.put(" Journey to the west "," Wu chengen ");
hashMap.put(" A dream of red mansions "," Cao xueqin ");
/*1、 First use keySet() Remove all key value , Then take out the corresponding value—— enhance for Loop traversal */
System.out.println("====1、 First use keySet() Remove all key value , Then take out the corresponding value—— enhance for Loop traversal ====");
Set keyset = hashMap.keySet();
for(Object key:keyset){
System.out.println(key+"-"+hashMap.get(key));
}
/*2、 First use keySet() Remove all key value , Then take out the corresponding value—— Use iterators to traverse */
System.out.println("====2、 First use keySet() Remove all key value , Then take out the corresponding value—— Use iterators to traverse ====");
Iterator iterator = keyset.iterator();
while(iterator.hasNext()){
Object key = iterator.next();
System.out.println(key+"-"+hashMap.get(key));
}
/*3、 adopt entrySet() get key-value value —— enhance for Loop traversal */
System.out.println("====3、 adopt entrySet() get key-value value —— enhance for Loop traversal ====");
Set set = hashMap.entrySet();
for(Object key:set){
Map.Entry entry = (Map.Entry) key;
System.out.println(entry.getKey()+"-"+entry.getValue());
}
/*4、 adopt entrySet() get key-value value —— Use iterators to traverse */
System.out.println("====4、 adopt entrySet() get key-value value —— Use iterators to traverse ====");
Set set1 = hashMap.entrySet();
Iterator iterator1 = set1.iterator();
while(iterator1.hasNext()){
Object itset = iterator1.next();
Map.Entry entry = (Map.Entry) itset;
System.out.println(entry.getKey()+"-"+entry.getValue());
}
}
}7、 Application, for example,
7.1 Problem description
Use HashMap add to 3 Employees , requirement
key : staff id
value : The employee object And traverse to display salary >18000 The employees' ( There are at least two traversal methods ) The employee class : full name 、 Wages 、 staff id
7.2 Code
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/* Use HashMap add to 3 Employees , requirement
key : staff id
value : The employee object
And traverse to display salary >18000 The employees' ( There are at least two traversal methods ) The employee class : full name 、 Wages 、 staff id
*/
public class MapExercise {
public static void main(String[] args) {
HashMap hashMap = new HashMap();
hashMap.put(1, new employee("Tom", 20000.0, 1));
hashMap.put(2, new employee("Jack", 10000.0, 2));
hashMap.put(3, new employee("Bob", 30000.0, 3));
hashMap.put(4, new employee("Marry", 17000.0, 4));
/*1、 adopt keySet() Get all key value , And get the corresponding value value —— enhance for Loop traversal */
System.out.println("====1、 adopt keySet() Get all key value , And get the corresponding value value —— enhance for Loop traversal ");
Set keyset = hashMap.keySet();
for (Object key : keyset) {
employee m = (employee) hashMap.get(key);
if (m.getSalary() > 18000) {
System.out.println(m);
}
}
/*2、 adopt entrySet() obtain key-value value —— Use iterators to traverse */
System.out.println("====2、 adopt entrySet() obtain key-value value —— Use iterators to traverse ====");
Set set = hashMap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object itset = iterator.next();
Map.Entry entry = (Map.Entry) itset;
employee m = (employee) entry.getValue();
if (m.getSalary() > 18000) {
System.out.println(m);
}
}
}
}
class employee{
private String name;
private Double salary;
private int id;
public employee(String name, Double salary, int id) {
this.name = name;
this.salary = salary;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "employee{" +
"name='" + name + '\'' +
", salary=" + salary +
", id=" + id +
'}';
}
}7.3 Running results

author :dengmsjava
https://blog.csdn.net/qq_40839718/article/details/123622684
official account “Java selected ” The published content indicates the source of , All rights reserved ( Those whose copyright cannot be verified or whose source is not indicated all come from the Internet , Reprinted , The purpose of reprinting is to convey more information , The copyright belongs to the original author . If there is any infringement , Please contact the , The author will delete the first time !
Many people have asked recently , Is there any readers Communication group ! The way to join is simple , official account Java selected , reply “ Add group ”, You can join the group !
Java Interview questions ( Wechat applet ):3000+ The road test questions , contain Java Basics 、 Concurrent 、JVM、 Threads 、MQ series 、Redis、Spring series 、Elasticsearch、Docker、K8s、Flink、Spark、 Architecture design, etc , Brush questions online at any time !
------ Special recommendation ------
Special recommendation : Focus on the most cutting-edge information and technology sharing , Official account for preparing for overtaking on curves and various open source projects and efficient software ,「 Big coffee notes 」, Focus on finding good things , It's worth your attention . Click the official account card below to follow .
If the article helps , Click to see , Forward! !
边栏推荐
- Explanation of tree chain dissection idea + acwing 2568 Tree chain dissection (DFS sequence + mountain climbing method + segment tree)
- Win10 install Apache Jena 3.17
- Paper notes: mind the gap an empirical evaluation of impaction ofmissing values techniques in timeseries
- Detailed explanation of Euler angle, axis angle, quaternion and rotation matrix
- LeetCode 2335. Minimum total time required to fill the cup
- Unity3d 读取mpu9250 例子原代码
- Documents required for military product development process - advanced version
- 【设计过程】.NET ORM FreeSql WhereDynamicFilter 动态表格查询功能
- (1) Learn about MySQL
- Pytoch learning record 2 linear regression (tensor, variable)
猜你喜欢

Explanation of tree chain dissection idea + acwing 2568 Tree chain dissection (DFS sequence + mountain climbing method + segment tree)

手机键盘(模拟题)

火箭大机动运动欧拉角解算的探讨

Evaluation method of machine learning model

军品研制过程所需文件-进阶版

Common collection properties

Journal日志与oplog日志的区别

人大、微软等提出InclusiveFL:异构设备上的包容性联邦学习

Configuration of vscode+unity3d

Opencv programming: opencv3 X trains its own classifier
随机推荐
基于“7·20郑州特大暴雨”对空天地一体化通信的思考
MySQL query error
【PostgreSQL 】PostgreSQL 15对distinct的优化
修改Jupyter默认路径看这篇!
LeetCode 2249. Count the number of grid points in the circle
6G智慧内生:技术挑战、架构和关键特征
About hping streaming test tool
input number 純數字輸入 限制長度 限制 最大值
LeetCode 745. 前缀和后缀搜索
【设计过程】.NET ORM FreeSql WhereDynamicFilter 动态表格查询功能
6G中的卫星通信高效天基计算技术
win10开始键点击无响应
2022/7/14
Pytoch realizes multi-layer perceptron manually
基于网络编码的卫星网络容量提升方法
String type function transfer problem
Maximal semi connected subgraph (tarjan contraction + topological ordering + DP longest chain)
Unity3d 读取mpu9250 例子原代码
Modify the default path of jupyter see this article!
Beego framework realizes file upload + seven cattle cloud storage
