开发手册 欢迎您!
软件开发者资料库

Java使用HashMap中的数据初始化HashMap并执行put数据的简洁代码

本文主要介绍Java中,避免代码重复来简洁实现,通过一个HashMap中的数据来初始另一个HashMap,调用get方法如存在,则返回HashMap并向其中put数据,如不存在则new一个HashMap也向其中put数据。

示例HashMap初始化重复操作如下:

HashMap> InitHashMap=getAll();HashMap allOrders=InitHashMap.get(id);if(allOrders!=null){    allOrders.put(date, order);      //<---REPEATED CODE}else{    allOrders = new HashMap<>();    allOrders.put(date, order);      //<---REPEATED CODE    InitHashMap.put(id, allOrders);}

1、使用computeIfAbsent()简单实现

 InitHashMap.computeIfAbsent(id, key -> new HashMap<>()).put(date, order);

相关文档Map#computeIfAbsent

2、使用containsKey(id)简单实现

if(!InitHashMap.containsKey(id))    InitHashMap.put(id, new HashMap());InitHashMap.get(id).put(date, Orders);

或者

HashMap allOrders =  InitHashMap.get(id);
if (allOrders == null) {
allOrders = new HashMap();
InitHashMap.put(id, allOrders);
}
allOrders.put(date, Orders);

3、HashMap常用操作代码

1) put方法插入数据

public static void main(String[] args) {         ///*Integer*/map.put("1", 1);//向map中添加值(返回这个key以前的值,如果没有返回null)         HashMap map=new HashMap<>();         System.out.println(map.put("1", 1));//null         System.out.println(map.put("1", 2));//1 }

2) get方法获取数据

public static void main(String[] args) {        HashMap map=new HashMap<>();        map.put("DEMO", 1);        /*Value的类型*///得到map中key相对应的value的值        System.out.println(map.get("1"));//null        System.out.println(map.get("DEMO"));//1  }

3) containsKey判断是否含有key

public static void main(String[] args) {        HashMap map=new HashMap<>();        /*boolean*///判断map中是否存在这个key        System.out.println(map.containsKey("DEMO"));//false        map.put("DEMO", 1);        System.out.println(map.containsKey("DEMO"));//true    }

4) containsValue判断是否包含value

public static void main(String[] args) {        HashMap map=new HashMap<>();        /*boolean*///判断map中是否存在这个value        System.out.println(map.containsValue(1));//false        map.put("DEMO", 1);        System.out.println(map.containsValue(1));//true    }

5) 显示所有的value值

public static void main(String[] args) {        HashMap map=new HashMap<>();        /*Collection*///显示所有的value值        System.out.println(map.values());//[]        map.put("DEMO1", 1);        map.put("DEMO2", 2);        System.out.println(map.values());//[1, 2]    }

6) 显示所有key和value

public static void main(String[] args) {        HashMap map=new HashMap<>();        /*SET>*///显示所有的key和value        System.out.println(map.entrySet());//[]        map.put("DEMO1", 1);        System.out.println(map.entrySet());//[DEMO1=1]        map.put("DEMO2", 2);        System.out.println(map.entrySet());//[DEMO1=1, DEMO2=2]    }

相关文档

Java putIfAbsent和computeIfAbsent使用说明及示例代码

Java HashMap computeIfAbsent()使用方法及示例代码