当前位置:网站首页>常用的遍历map的方法
常用的遍历map的方法
2022-08-05 07:13:00 【MrLee528】
常用的遍历map的方法
package com.lxh.config.utils;
import java.util.*;
/** * @ClassName: commonUtil * @Author: lxh * @Description: 公共方法工具类 * @Date: 2022/4/14 14:53 */
public class CommonMethods {
public static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("id", 1);
map.put("name", "lxh");
map.put("age", 18);
getMap(1, map);
getMap(2, map);
getMap(3, map);
getMap(4, map);
getMap(5, map);
}
/** * 遍历map */
public static void getMap(Integer type, Map<String, Object> map) {
if (type == 1) {
System.out.println("============通过map.keySet()的key获取value===========");
Set<String> set = map.keySet();
set.forEach(item -> {
System.out.println(item + ": " + map.get(item));
});
} else if (type == 2) {
System.out.println("============通过map.entrySet()的实体去获取key跟value===========");
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
entrySet.forEach(item -> {
System.out.println(item.getKey() + ": " + item.getValue());
});
} else if (type == 3) {
System.out.println("=============通过迭代器获取key跟value==========");
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
} else if (type == 4) {
System.out.println("============通过map.values()获取value,不能获取key===========");
map.values().forEach(System.out::println);
} else if (type == 5) {
System.out.println("============通过lambda表达式获取key跟value===========");
map.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
}
边栏推荐
猜你喜欢
随机推荐
Mysql为什么 建立数据库失败
每一个女孩曾经都是一个没有泪的天使
Flink学习11:flink程序并行度
不能比较或排序 text、ntext 和 image 数据类型
软件测试必问面试题(附答案和解析)
A small problem with mysql using the in function
TRACE32——加载符号表信息用于调试
protobuf is compiled against the associated .proto file
Mysql master-slave delay reasons and solutions
2022.7.29好题选讲(计数专题)
RNote108---Display the running progress of the R program
Mysql主从延迟的原因和解决方案
奇怪的Access错误
算法拾遗十五补链表相关面试题
ARM Cortex-M上的Trace跟踪方案
Redis
强网杯2022 pwn 赛题解析——house_of_cat
Flink学习12:DataStreaming API
Shiny04---DT和进度条在shiny中的应用
栈与队列的基本介绍和创建、销毁、出入、计算元素数量、查看元素等功能的c语言实现,以及栈的压入、弹出序列判断,栈结构的链式表示与实现









