How to conditionally insert a Map into a list in Java if the list does not already include a map containing a key value pair

huangapple go评论77阅读模式
英文:

How to conditionally insert a Map into a list in Java if the list does not already include a map containing a key value pair

问题

我有一个在Java中的HashMap对象列表。
如果列表中尚不存在具有与新HashMap中相同的键值对的HashMap,则我想要有条件地将更多的HashMap对象添加到此列表中。

以下是一个HashMap列表的示例。请注意,实际上有更多的键。这里,我只包括了"contact_id",以简化。

[{contact_id=16247115}, {contact_id=16247116}, {contact_id=16247117}, {contact_id=16247118}, {contact_id=16247119}]

不应允许将{contact_id=16247117}添加到此列表中。
应允许添加{contact_id=74857983}

理想情况下,我希望能够以一行代码有条件地将多个HashMap添加到此列表中。如果我不执行条件检查,我可以使用语法listname.addAll(batchOfHashMaps)。我想做类似的事情,但排除列表中的冗余HashMap。

在Java中实现此条件插入的最有效方法是什么?

我认为必须有一种比在for循环中评估列表中的每个元素更有效的解决方案。

英文:

I have a list of HashMap objects in Java.
I would like to conditionally add more HashMap objects to this list if the list does not already contain a HashMap having the same key value pair as in the new HashMap.

Here is an example HashMap list. Note that in reality, there are more keys. Here, I am just including "contact_id" for simplicity.

[{contact_id=16247115}, {contact_id=16247116}, {contact_id=16247117}, {contact_id=16247118}, {contact_id=16247119}]

Adding {contact_id=16247117} to this list should not be allowed.
Adding {contact_id = 74857983}, should be allowed.

Ideally, I would like to be able to conditionally add several HashMaps into this list in one line of code. If I were not to perform the conditional check, I could just use the syntax listname.addAll(batchOfHashMaps). I'd like to do something similar, but precluding redundant HashMaps in the list.

What is the most efficient way to achieve this conditional insert in Java?

I reckon there must be a more efficient solution than evaluating each element in the list inside a for-loop.

答案1

得分: 2

如果你只想查看地图中的一个键值对作为标识符,那么你可以使用Map来代替List来保存所有内容。例如,
Map<String, Map<String, String>> mapOfMaps;

然后你可以像这样添加一个:

mapOfMaps.putIfAbsent(mapToAdd.get("contact_id"), mapToAdd);

你也可以像这样添加多个:

batchOfHashMaps.forEach(m -> mapOfMaps.putIfAbsent(m.get("contact_id"), m));

要获取你的地图集合,只需调用values()方法:

mapOfMaps.values();
英文:

If you are only wanting to look at one key-value pair of the maps as an identifier, then you could use a Map instead of a List to hold everything. For example,
Map<String, Map<String, String> mapOfMaps;

Then you could add one like:

mapOfMaps.putIfAbsent(mapToAdd.get(&quot;contact_id&quot;), mapToAdd);

you could add multiple like:

batchOfHashMaps.forEach(m -&gt; mapOfMaps.putIfAbsent(m.get(&quot;contact_id&quot;), m));

To get a collection of your maps simply call values()

mapOfMaps.values();

huangapple
  • 本文由 发表于 2020年8月5日 08:24:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63256744.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定