[英]Searching a HashMap<String, Arraylist<Users>> or HashMap<String, HashSet<Users>>
I need to search through a HashMap
that contains a key/value of either String, ArrayList<Users>
or String, HashSet<Users>
for a given value. 我需要搜索一个
HashMap
,其中包含给定值的String, ArrayList<Users>
/ String, ArrayList<Users>
或String, HashSet<Users>
的键/值。 I am unsure how to write the code to do this in java. 我不确定如何编写代码以在Java中执行此操作。
I declared.. 我宣布
private HashMap<String, ArrayList<Users>> cm = new HashMap<>();
my method that needs to be called to search looks like this... 我需要搜索的方法看起来像这样...
public void doSomething(User u, String product) {
}
so I'm unsure of how the code inside the method would work. 所以我不确定方法中的代码如何工作。
if (cm.containsKey(product) {
//This is where I'm unsure if I find the key on how to check if the ArrayList has a
particular user. And then if not how to add them.
}
I'm not sure exactly how to do it, but I asked a question a few days ago concerning map entry sets and using '?' 我不确定该怎么做,但是几天前我问了一个有关地图条目集和使用'?'的问题。 to allow multiple types.
允许多种类型。 The answer I accepted was well explained and comes with an example.
我接受的答案已得到很好的解释,并附带一个示例。 Might help you out.
可能会帮助您。
Your User
addition method could look like this: 您的
User
添加方法如下所示:
public void doSomething(User user, String product) {
if (cm.containsKey(product)) {
List<User> list = cm.get(product);
if (!list.contains(user)) {
list.add(user);
}
}
}
This assumes that you define your HashMap
with a single User
type: 假定您使用单个
User
类型定义HashMap
:
HashMap<String, ArrayList<User>> cm = new HashMap<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.