前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java数据结构精进:优化HashMapList的冗余设计

Java数据结构精进:优化HashMapList的冗余设计

原创
作者头像
Nimyears
修改2024-07-15 10:51:39
1170
修改2024-07-15 10:51:39

HashMapList<T, E>

HashMapList类本质上是HashMap<T, Arraylist<E>>的简写,从类型为 T 的项映射到类型为 E 的 Arraylist。

冗余代码

代码语言:java
复制
 	HashMap<Integer, Arraylist<String>> maplist = new HashMap<Integer, Arraylist<String>>();
 	  for (String s : strings) {
 		int key = computeValue(s);
  		if (!maplist.containsKey(key)) {
 			maplist.put(key, new Arraylist<String>());
 	}
 		maplist.get(key).add(s);
 	}

现在,可以这样写为:

代码语言:java
复制
   HashMaplist<Integer, String> maplist new HashMapList<Integer, String>();
        for (String s : strings) {
            int key = computeValue(s);
            if (!maplist.computeValue(s));
            maplist.put(key, s);
         }

代码实现

HashMapList<T, E>类中:

  • T 通常代表键(key)的类型。
  • E 通常代表值(value)的类型。
代码语言:java
复制
public class HashMapList<T, E> {
    private HashMap<T, Arraylist<E>> map = new HashMap<T, Arraylist<E>>();

    /* key插入项item*/
    public void put(T key, E item) {
        if (!map.containsKey(key)) {
            map.put(key, new Arraylist<E>());
        }
        map.get(key).add(item);
    }

    /* 键key插入项列表*/
    public void put(T key, Arraylist<E> items) {
        map.put(key, items);
    }

    /* 获取key的项列表 */
    public Arraylist<E> get(T key) {
        return map.get(key);
    }

    /* 检查hashmaplist是否包含key*/
    public boolean containsKey(T key) {
        return map.containsKey(key);
    }

    /* 检查key的列表是否包含value*/
    public boolean containsKeyValue(T key, E value) {
        Arraylist<E> list = get(key);
        if (list == null) return false;
        return list.contains(value);
    }

    /* 获取key列表*/
    public Set<T> keySet() {
        return map.keySet();
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

使用示例

代码语言:java
复制
public class HashMapListExample {
    public static void main(String[] args) {
        //创建一个HashMapList
        HashMapList<String, Integer> mapList = new HashMapList<>();
        //mapList添加数据
        mapList.put("年龄", 25);
        mapList.put("年龄", 30);
        mapList.put("分数", 85);
        mapList.put("分数", 90);
        //输出整个mapList
        System.out.println(mapList.toString());
        //获取键"年龄"下的全部值
        ArrayList<Integer> ages = mapList.get("年龄");
        System.out.println("年龄列表: " + ages.toString());
        //检查是否包含键"分数"
        boolean Scores = mapList.containsKey("分数");
        System.out.println("是否包含'分数'键: " + Scores);
    }
}

结论

HashMapList类提供了管理键和列表的映射关系,减少了代码冗余,提高了代码的可读性和维护性。

谢谢大家阅读:)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • HashMapList<T, E>
    • 冗余代码
      • 代码实现
        • 使用示例
          • 结论
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档