gpt4 book ai didi

java - 推送到列表的 HashMap

转载 作者:行者123 更新时间:2023-12-01 19:39:02 25 4
gpt4 key购买 nike

我正在尝试创建一个像这样的结构:

{
id1: [item1, item2, item3],
id2: [item2, item3, item4]
}

跟踪每个 ID 拥有的项目。

我知道我可以使用以下形式的 HashMap 来实现此目的:HashMap<ID, ArrayList<Items>>

但随后我会不断地先发制人地检查 ID: ArrayList<Items> 是否存在,并在推送 Item 之前,当某个 ID 不存在时实例化一个新的空数组列表。

是否有更专业的类可以用来完成这种形式的结构,或者这种检查是不可避免的。

我想要这样的东西:

entries = new SomeMapListClass<ID, Item>();
entries.put(ID, ...Items); // handles array internally
Items[] = entries.get(ID);

我事先不知道 ID,所以我最初无法用空数组填充 HashMap。

最佳答案

But then I'd constantly be pre-emptively checking for the existence of the ID: ArrayList, and instantiating a new empty array list when one doesn't exist for an ID, before pushing the Item.

这是完全可以接受的,并且 Map接口(interface)提供了帮助您完成此操作的方法。例如:

Map<ID, List<Items>> map = new HashMap<>();

map.computeIfAbsent(id, $ -> new ArrayList<>()).add(item);

就这么简单,因为 Map#computeIfAbsent 返回映射值(如果存在),如果不存在则返回计算值。

因此,为了回答您的问题,Map<ID, List<Items>>在这种情况下使用完全没问题。

关于java - 推送到列表的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56050792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com