2012-10-22 159 views
0

我需要通過包含的任String, ArrayList<Users>String, HashSet<Users>對於給定的值的鍵/值的HashMap進行搜索。我不確定如何編寫代碼來在java中執行此操作。搜索一個HashMap <字符串,ArrayList的<Users>>或HashMap中<字符串,HashSet的<Users>>

我宣佈..

private HashMap<String, ArrayList<Users>> cm = new HashMap<>(); 

我的方法需要被稱爲搜索看起來像這樣...

public void doSomething(User u, String product) { 

} 

所以我不能確定的是如何在方法內部的代碼會工作。

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. 
} 
+0

你的代碼是不syntatically正確。您可以請在這裏發佈您的真實代碼請 – smk

+0

此外,您的問題是模糊的。請告訴你已經嘗試了什麼。 – smk

回答

0

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); 
     } 
    } 
} 

這是假設你定義你HashMap與單一User類型:

HashMap<String, ArrayList<User>> cm = new HashMap<>(); 
+0

這工作。謝謝! – user1741700

0

我不確定如何做到這一點,但幾天前我問了一個關於地圖輸入集和使用'?'的問題。允許多種類型。我接受的答案很好解釋並附帶一個例子。可以幫助你。

Trouble understanding Java map Entry sets

+0

我來看看。 – user1741700

相關問題