TestMap
public class TestMap {
public static void main(String[] args) {
Map map=new HashMap();
//在此映射中关联指定值与指定键。
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value2");
map.put("key4", "value4");
map.put("key5", "value5");
map.put("key6",null);
map.put(null,null);
System.out.println(map.size());
System.out.println(map.get(null));
for(int i=1;i<map.size();i++){
System.out.println(map.get(i));
}
Iterator it=map.keySet().iterator();
while(it.hasNext()){
Object key=it.next();
Object value=map.get(key);
System.out.println("key="+key+"-->"+"value="+value);
}
Iterator itt=map.entrySet().iterator();
while(itt.hasNext()){
System.out.println(itt.next());
}
Iterator it2=map.entrySet().iterator();
while(it2.hasNext()){
Map.Entry key=(Map.Entry) it2.next();
System.out.println("key="+key.getKey()+"-->"+"value="+key.getValue());
}
}
}
HashMap
package com.example.demo;
import org.testng.annotations.Test;
import java.util.HashMap;
public class TestHashMap {
@Test(description = "Hashmap的存值")
public void TestPut() {
///*Integer*/map.put("1", 1);
// 向map中添加值(返回这个key以前的值,如果没有返回null)
HashMap<String, Integer> map=new HashMap<>();
Integer flag_a = map.put("1", 1);
Integer flag_b = map.put("1", 2);
System.out.println(flag_a);//null
System.out.println(flag_b);//1
}
@Test(description = "Hashmap的取值")
public void TestGet() {
HashMap<String, Integer> map=new HashMap<>();
map.put("key", 1);
/*Value的类型*///得到map中key相对应的value的值
System.out.println(map.get("1"));//null
System.out.println(map.get("key"));//1
}
@Test(description = "Hashmap的判断为空")
public void TestCheckEmpty() {
HashMap<String, Integer> map=new HashMap<>();
/*boolean*///判断map是否为空
System.out.println(map.isEmpty());//true
map.put("key", 1);
System.out.println(map.isEmpty());//false
}
@Test(description = "Hashmap判断是否含有key")
public void TestCheckKey() {
HashMap<String, Integer> map=new HashMap<>();
/*boolean*///判断map中是否存在这个key
System.out.println(map.containsKey("key"));//false
map.put("key", 1);
System.out.println(map.containsKey("key"));//true
}
@Test(description = "Hashmap判断是否含有value")
public void TestCheckValue() {
HashMap<String, Integer> map=new HashMap<>();
/*boolean*///判断map中是否存在这个value
boolean flag_a = map.containsValue(1);
System.out.println(flag_a);//false
map.put("key", 1);
boolean flag_b = map.containsValue(1);
System.out.println(flag_b);//true
}
@Test(description = "Hashmap删除这个key值下的value")
public void TestDelValue() {
HashMap<String, Integer> map=new HashMap<>();
/*Integer*///删除key值下的value
Integer result =map.remove("key1");
System.out.println(result);//null
map.put("key1", 2);
System.out.println(map.remove("key1"));//2(删除的值)
}
@Test(description = "Hashmap显示所有的value值")
public void TestGetAllValue() {
HashMap<String, Integer> map=new HashMap<>();
/*Collection<Integer>*///显示所有的value值
System.out.println(map.values());//[]
map.put("key1", 1);
map.put("key2", 2);
System.out.println(map.values());//[1, 2]
}
@Test(description = "Hashmap的元素个数")
public void TestGetNumber() {
HashMap<String, Integer> map=new HashMap<>();
/*int*///显示map里的值得数量
System.out.println(map.size());//0
map.put("key1", 1);
System.out.println(map.size());//1
map.put("key2", 2);
System.out.println(map.size());//2
}
@Test(description = "Hashmap删除这个key值下的value")
public void TestDelKeysValue() {
HashMap<String, Integer> map=new HashMap<>();
/*SET<String>*///显示map所有的key
System.out.println(map.keySet());//[]
map.put("key1", 1);
System.out.println(map.keySet());//[key1]
map.put("key2", 2);
System.out.println(map.keySet());//[key1, key2]
}
@Test(description = "Hashmap删除这个key值下的value")
public void TestShow() {
HashMap<String, Integer> map=new HashMap<>();
/*SET<map<String,Integer>>*///显示所有的key和value
System.out.println(map.entrySet());//[]
map.put("key1", 1);
System.out.println(map.entrySet());//[key1=1]
map.put("key2", 2);
System.out.println(map.entrySet());//[key1=1, key2=2]
}
@Test(description = "Hashmap添加另一个同一类型的map下的所有内容")
public void TestContainShow() {
HashMap<String, Integer> map=new HashMap<>();
HashMap<String, Integer> map1=new HashMap<>();
/*void*///将同一类型的map添加到另一个map中
map1.put("key11", 1);
map.put("key", 2);
System.out.println(map);//{key=2}
map.putAll(map1);
System.out.println(map);//{key11=1, key11=2}
}
@Test(description = "Hashmap删除这个key和value")
public void TestDelKeyandValue() {
HashMap<String, Integer> map=new HashMap<>();
/*boolean*///删除这个键值对
map.put("TestDelKeyandValue1", 1);
map.put("TestDelKeyandValue2", 2);
System.out.println(map);//{DEMO1=1, DEMO2=2}
System.out.println(map.remove("TestDelKeyandValue2", 1));//false
System.out.println(map.remove("TestDelKeyandValue2", 2));//true
System.out.println(map);//{TestDelKeyandValue1=1}
}
@Test(description = "Hashmap替换这个key的value:(java8)")
public void TestReplaceValue() {
HashMap<String, Integer> map=new HashMap<>();
/*value*///判断map中是否存在这个key
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
System.out.println(map);//{key1=1, key2=2}
System.out.println(map.replace("key2", 22));//2
System.out.println(map.replace("key3", 33));//3
System.out.println(map);//{key1=1, key2=22}
}
@Test(description = "清空这个hashmap")
public void TestClear() {
HashMap<String, Integer> map=new HashMap<>();
/*void*///清空map
map.put("key1", 1);
map.put("key2", 2);
System.out.println(map);//{key1=1, key2=2}
map.clear();//2
System.out.println(map);//{}
}
@Test(description = "Hashmap的克隆")
public void TestClone() {
HashMap<String, Integer> map=new HashMap<>();
/*object*///克隆这个map
map.put("DEMO1", 1);
map.put("DEMO2", 2);
System.out.println(map.clone());//{DEMO1=1, DEMO2=2}
Object clone = map.clone();
System.out.println(clone);//{DEMO1=1, DEMO2=2}
}
}
(java8新增方法)
如果当前 Map 不存在键 key 或者该 key 关联的值为 null,那么就执行 put(key, value);否则,便不执行 put 操作
public static void main(String[] args) {
HashMap<String, Integer> map=new HashMap<>();
/*boolean*///判断map中是否存在这个key
map.put("DEMO1", 1);
map.put("DEMO2", 2);
System.out.println(map);//{DEMO1=1, DEMO2=2}
System.out.println(map.putIfAbsent("DEMO1", 12222));//1
System.out.println(map.putIfAbsent("DEMO3", 12222));//null
System.out.println(map);//{DEMO1=1, DEMO2=2}
}
如果当前 Map 的value为xx时则值为xx否则为xx:(java8新增方法)compute 方法更适用于更新 key 关联的 value 时,新值依赖于旧值的情况
public static void main(String[] args) {
HashMap<String, Integer> map=new HashMap<>();
/*boolean*///当这个value为null时为1,否则为3
map.put("DEMO1", 1);
map.put("DEMO2", 2);
System.out.println(map);//{DEMO1=1, DEMO2=2}
map.compute("DEMO2", (k,v)->v==null?1:3);
System.out.println(map);//{DEMO1=1, DEMO2=3}
}
我们提一个需求:给定一个 List<String>,统计每个元素出现的所有位置。
比如,给定 list:["a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"] ,那么应该返回:
a : [0]
b : [1, 2]
c : [3, 4, 5]
d : [6, 7, 8]
f : [9, 10]
g : [11]
很明显,我们很适合使用 Map 来完成这件事情:
package com.example.demo;
import java.util.*;
public class TestSort {
public static Map<String, List<Integer>> getElementPositions(List<String> list) {
Map<String, List<Integer>> positionsMap = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
List<Integer> positions = positionsMap.get(str);
if (positions == null) { // 如果 positionsMap 还不存在 str 这个键及其对应的 List<Integer>
positions = new ArrayList<>(1);
positionsMap.put(str, positions); // 将 str 及其对应的 positions 放入 positionsMap
}
positions.add(i); // 将索引加入 str 相关联的 List<Integer> 中
}
return positionsMap;
}
public static void main(String[] args) throws Exception {
List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g");
System.out.println("使用 Java8 之前的 API:");
Map<String, List<Integer>> elementPositions = getElementPositions(list);
System.out.println(elementPositions);
}
}

Java8 时,Map<K, V> 接口添加了一个新的方法,putIfAbsent(K key, V value),功能是:
如果当前 Map 不存在键 key 或者该 key 关联的值为 null,那么就执行 put(key, value);否则,便不执行 put 操作
package com.example.demo;
import java.util.*;
public class TeatSort2 {
public static Map<String, List<Integer>> getElementPositions(List<String> list) {
Map<String, List<Integer>> positionsMap = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
positionsMap.putIfAbsent(str, new ArrayList<>(1)); // 如果 positionsMap 不存在键 str 或者 str 关联的 List<Integer> 为 null,那么就会进行 put;否则不执行 put
positionsMap.get(str).add(i);
}
return positionsMap;
}
public static void main(String[] args) throws Exception {
List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g");
System.out.println("使用 putIfAbsent:");
Map<String, List<Integer>> elementPositions = getElementPositions(list);
System.out.println(elementPositions);
}
}

https://segmentfault.com/a/1190000007838166
TestMap的更多相关文章
- TODO:Golang指针使用注意事项
TODO:Golang指针使用注意事项 先来看简单的例子1: 输出: 1 1 例子2: 输出: 1 3 例子1是使用值传递,Add方法不会做任何改变:例子2是使用指针传递,会改变地址,从而改变地址. ...
- 4. ValueStack 和 OGNL
1. 属性哪来的 当我们通过Action处理完用户请求以后,可以直接在页面中获取到 action 的属性值. 如果我们在页面中尝试遍历四个域中的属性,会发现域中并没有username之类的Action ...
- Spring MVC学习
SpringMVC框架 转载请注明出处 目录 一:配置springMVC开发环境 1.1.配置文件的helloworld 1.2.基于注解的helloworld 二:@RequestMapping详解 ...
- Strust OGNL详解
首先了解下OGNL的概念: OGNL是Object-Graph Navigation Language的缩写,全称为对象图导航语言,是一种功能强大的表达式语言,它通过简单一致的语法,可以任意存取对象的 ...
- RedisUtil 工具类
package com.test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import red ...
- Spring + Jedis集成Redis(集群redis数据库)
前段时间说过单例redis数据库的方法,但是生成环境一般不会使用,基本上都是集群redis数据库,所以这里说说集群redis的代码. 1.pom.xml引入jar <!--Redis--> ...
- Struts2的OGNL表达式语言
一.OGNL的概念 OGNL是Object-Graph Navigation Language的缩写,全称为对象图导航语言,是一种功能强大的表达式语言,它通过简单一致的语法,可以任意存取对象的属性或者 ...
- 跟我一起数据挖掘(21)——redis
什么是Redis Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis的开发工 ...
- 【Java心得总结七】Java容器下——Map
我将容器类库自己平时编程及看书的感受总结成了三篇博文,前两篇分别是:[Java心得总结五]Java容器上——容器初探和[Java心得总结六]Java容器中——Collection,第一篇从宏观整体的角 ...
随机推荐
- C#遍历枚举(Enum)值
foreach (object o in Enum.GetValues(typeof(EmpType))) { Console.WriteLine("{0}:{1}", o, En ...
- Linux re
正则表达式并不是一个工具程序,而是一个字符串处理的标准依据,如果想要以正则表达式的方式处理字符串,就得使用支持正则表达式的工具,例如grep.vi.sed.asw等. 注意:ls不支持正则表达式. g ...
- ASP.NET常见异常处理示例
将指定的年月日转初始化为DateTime新的实例(Nop.Admin.Controllers.OrderController.ParseProductAttributes) case Attribut ...
- Codeforces 1136E - Nastya Hasn't Written a Legend - [线段树+二分]
题目链接:https://codeforces.com/problemset/problem/1136/E 题意: 给出一个 $a[1 \sim n]$,以及一个 $k[1 \sim (n-1)]$, ...
- Hyper-v带宽限制以及验证工具
最近在做项目的性能测试时,需要模拟网络的带宽来控制文件的上传速度.按照以前的方式方法,我们一般会使用工具 softperfect bandwidth manager 来模拟上下行的带宽. 官网地址 h ...
- vue:不同环境配置不同打包命令
修改prod.env.js 'use strict'const target = process.env.npm_lifecycle_event;if (target == 'build') { // ...
- C#编程基础(简单概述与理解)
1.C#变量和数据输入 C#常用到的几个数据类型: 整型:int 说明:32位有符号整数 范围:-2³¹~2³¹-1 浮点型:double 说明:64位双精度浮点数 范围:±5.0×10-﹣³²~± ...
- java框架之SpringCloud(3)-Eureka服务注册与发现
在上一章节完成了一个简单的微服务案例,下面就通过在这个案例的基础上集成 Eureka 来学习 Eureka. 介绍 概述 Eureka 是 Netflix 的一个子模块,也是核心模块之一.Eureka ...
- Django进阶之中间件
中间件简介 django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法. 在djang ...
- 初入MEF-IOC导入导出
DDD,领域驱动开发,听起来高端大气,这本书买回来翻了几下,实在是晦涩难懂