HashMap使用及完整测试用例

1.常用方法

  • put(key, value))

添加元素时,如果key已经存在,则返回旧value,并将新的value存到该key中;如果key不存在,则返回null
当key=null时,并不会抛出异常,而是按照一个特殊的方法进行存储

  • putIfAbsent(key,value):

与put的区别:如果key存在且value不为null,则不会覆盖原有的value

  • get(key):

key存在时返回对应value,key不在时返回null

  • getOrDefault(key, defaultValue):

在key不存在时,返回一个defaultValue

  • replace(key, value)):

对于存在的key,调用replace方法,会替换原来的value,并返回旧value;
对于不存在的key,replace方法什么都不做,返回null

  • forEach(BiConsumer<K, V> action):

对每个映射项执行action操作:通常传入lambda表达式作为匿名函数

2.超类Map的方法和属性

  • keySet():

该方法返回值是Map中key值的Set集合,形式:Set keySet = someMap.keySet();

  • values():

返回 HashMap 中所有 value 值所组成的 collection view(集合视图),形式:Collection values = someMap.values();

  • entrySet():

该方法返回值是一个Set集合,此集合的成员对象类型为Map.Entry,形式:Set<Map.Entry<String, String>> entries = someMap.entrySet();

  • Map.Entry

Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>;表示Map中的一个实体(一个key-value对)
获取实体中的key:getKey();获取实体的value:getValue()

3.测试用例及输出结果

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Collection;
import java.util.Set;

public class hashmap {
    public static void main(String[] args) {
        // 创建 HashMap 对象
        Map<String, Integer> hashMap = new HashMap<String, Integer>();

        // 添加元素(key,value)
        System.out.println("添加(aa,1)返回:" + hashMap.put("aa", 1));
        System.out.println("添加(bb,2)返回:" + hashMap.put("bb", 2));
        System.out.println("再次添加key bb返回值:" + hashMap.putIfAbsent("bb", 20));
        System.out.println("第一次添加key cc返回值:"  + hashMap.put("cc", 3));
        System.out.println("再次添加key cc返回值:" + hashMap.put("cc", 4));
        System.out.println("替换key cc返回值:" + hashMap.replace("cc", 3));
        System.out.println("替换key ccc返回值:" + hashMap.replace("ccc", 3));
        System.out.println("");
        // 读取元素
        System.out.println("读取元素:");
        System.out.println("获取key 'aa'的值:" + hashMap.get("aa"));
        System.out.println("获取key 'aaa'的值" + hashMap.get("aaa"));
        System.out.println("获取key 'aaa'的值" + hashMap.getOrDefault("aaa", 0));
        //判断key或value是否存在
        System.out.println("key aa是否存在:" + hashMap.containsKey("aa"));
        System.out.println("value 1是否存在:" + hashMap.containsValue(1));
        System.out.println("map中元素个数:" + hashMap.size());
        System.out.println("");

        // foreach遍历
        System.out.println("foreach遍历映射项(实体):");
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ",value = " + entry.getValue());
        }
        System.out.println("foreach遍历映射项的键值:");
        for (String key : hashMap.keySet()) {
            System.out.println("Key = " + key);
        }
        System.out.println("foreach遍历映射项的value值:");
        for (Integer value : hashMap.values()) {
            System.out.println("Value = " + value);
        }
        System.out.println("");

        // Iterator迭代器遍历
        System.out.println("Iterator遍历映射项(实体):");
        // 使用带泛型的迭代器: Iterator<Map.Entry<String, Integer>>, 因为创建HahsMap对象使用泛型化了
        Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer>  entry = iterator.next();
            System.out.println("Key = " + entry.getKey() + ",value = " + entry.getValue());
        }
        System.out.println("Iterator遍历映射项键值:");
        Iterator<String> iterator2 = hashMap.keySet().iterator();
        while (iterator2.hasNext()) {
            String key = iterator2.next();
            System.out.println("Key = " + key);
        }
        System.out.println("Iterator遍历映射项值:");
        Iterator<Integer> iterator3 = hashMap.values().iterator();
        while (iterator3.hasNext()) {
            Integer value = iterator3.next();
            System.out.println("value = " + value);
        }
        System.out.println("");

        // 使用lambda表达式
        System.out.println("lambda表达式遍历映射项:");
        hashMap.forEach((k,v) -> System.out.println("key = " +k + ",value = " + v));
        System.out.println("");

        // 使用Stream
        System.out.println("使用stream遍历映射项:");
        hashMap.entrySet().stream().forEach(entry -> System.out.println("Key = " + entry.getKey() + ",value = " + entry.getValue()));
        System.out.println("使用parrallelStream遍历映射项:");
        hashMap.entrySet().parallelStream().forEach(entry -> System.out.println("Key = " + entry.getKey() + ",value = " + entry.getValue()));
        System.out.println("");

        // hampMap转换为集合
        System.out.println("hampMap转换为集合:");
        Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
        System.out.println("映射项的集合:" + entries);
        Set<String> keys = hashMap.keySet();
        System.out.println("键值的集合:" + keys);
        Collection<Integer> values = hashMap.values();
        System.out.println("value的集合:" + values);
        System.out.println("");

        // 删除元素
        hashMap.remove("aa");
        System.out.println(hashMap);

        // 清空map
        hashMap.clear();
        System.out.println(hashMap);
    }
}

输出结果:

添加(aa,1)返回:null
添加(bb,2)返回:null
再次添加key bb返回值:2
第一次添加key cc返回值:null
再次添加key cc返回值:3
替换key cc返回值:4
替换key ccc返回值:null

读取元素:
获取key 'aa'的值:1
获取key 'aaa'的值null
获取key 'aaa'的值0
key aa是否存在:true
value 1是否存在:true
map中元素个数:3

foreach遍历映射项(实体):
Key = aa,value = 1
Key = bb,value = 2
Key = cc,value = 3
foreach遍历映射项的键值:
Key = aa
Key = bb
Key = cc
foreach遍历映射项的value值:
Value = 1
Value = 2
Value = 3

Iterator遍历映射项(实体):
Key = aa,value = 1
Key = bb,value = 2
Key = cc,value = 3
Iterator遍历映射项键值:
Key = aa
Key = bb
Key = cc
Iterator遍历映射项值:
value = 1
value = 2
value = 3

lambda表达式遍历映射项:
key = aa,value = 1
key = bb,value = 2
key = cc,value = 3

使用stream遍历映射项:
Key = aa,value = 1
Key = bb,value = 2
Key = cc,value = 3
使用parrallelStream遍历映射项:
Key = aa,value = 1
Key = bb,value = 2
Key = cc,value = 3

hampMap转换为集合:
映射项的集合:[aa=1, bb=2, cc=3]
键值的集合:[aa, bb, cc]
value的集合:[1, 2, 3]

{bb=2, cc=3}
{}
java hashmap  0.13s user 0.06s system 145% cpu 0.130 total

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个基于Java JUnit框架的简单定时任务单元测试用例示例: ```java import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.*; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; public class MyTaskTest { @Mock private MyService myService; // 模拟依赖的服务对象 @InjectMocks private MyTask myTask; // 待测试的任务对象 @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); // 初始化Mockito } @Test public void testTaskExecution() { // 模拟任务执行时间 LocalDateTime executionTime = LocalDateTime.now().plusMinutes(5); // 模拟任务执行参数 Map<String, Object> args = new HashMap<>(); args.put("arg1", "value1"); args.put("arg2", "value2"); // 模拟服务返回值 when(myService.getData(anyString())).thenReturn("test data"); // 执行任务 myTask.run(args); // 验证任务执行结果 verify(myService, times(1)).saveData(eq("test data")); // 验证任务执行时间 assertEquals(myTask.getLastExecutionTime(), executionTime); // 验证任务执行参数 assertEquals(myTask.getLastExecutionArgs(), args); } @Test public void testTaskExceptionHandling() { // 模拟任务执行时间 LocalDateTime executionTime = LocalDateTime.now().plusMinutes(5); // 模拟任务执行参数 Map<String, Object> args = new HashMap<>(); args.put("arg1", "value1"); args.put("arg2", "value2"); // 模拟服务异常 when(myService.getData(anyString())).thenThrow(new RuntimeException("test exception")); // 执行任务 myTask.run(args); // 验证任务执行结果 verify(myService, never()).saveData(anyString()); // 验证任务执行时间 assertEquals(myTask.getLastExecutionTime(), executionTime); // 验证任务执行参数 assertEquals(myTask.getLastExecutionArgs(), args); } } ``` 上述示例中,我们针对待测试的定时任务类`MyTask`编写了两个测试用例,分别测试了任务的正常执行和异常处理情况。在测试用例中,我们使用了`Mockito`框架来模拟任务的执行环境,包括依赖的服务对象、任务执行时间、执行参数以及执行结果等等。最后,我们使用`verify`方法来验证任务执行的结果是否符合预期,使用`assertEquals`方法来验证任务执行的时间和参数是否符合预期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值