mykael
mykael

Reputation: 21

edit hashmap with hashset as value

I have the following code:

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(name.equals(base))
        {

        }
}

listB is an array with Person elements.

So, if a Person's name matches the String base, they are getting attached to a pair of key-value in the index HashMap. The HashSet for each key contains the Persons that their name matches the String base. How can this be done?

Also, I have a method like:

public void printPersons(String sth)
{

}

that I want it to print the persons contained in the HashSet of the key called each time.

Thank you

Upvotes: 0

Views: 3739

Answers (3)

Tahir Hussain Mir
Tahir Hussain Mir

Reputation: 2626

Do this

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
HashSet<Person> h = new HashSet<String>();
    for(Person i: listB)
    {
        //I assume it is i.name here
        if(i.name.equals(base))
        {
            h.add(i);
        }
    }
     index.put(base,h);
}

And for printing, do this

public void printPersons(String sth)
{
    Map mp = index.get(sth);
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
    }
}

Upvotes: 0

Derrick
Derrick

Reputation: 4417

Instead of creating HashSet object in every iteration, create it only when name matches like in the below code -

public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(index.containsKey(base)){
            HashSet<Person> existingHS = index.get(base);
            existingHS.add(i);
            index.put(base,existingHS);
        }else{
            HashSet<Person> hs = new HashSet<Person>();
            hs.add(i);
            index.put(base,hs);
        }
}

Upvotes: 0

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

Use putIfAbsent to insert an empty hash set place holder.

Then add new person to existing set:

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(name.equals(base))
        {
            index.putIfAbsent(base, new HashSet<>());
            index.get(base).add(i)
        }
}

Note: In order to correctly add person to set, you have to implement equals()/hashCode() for your Person class, since Set use equals() to determine uniqueness

Upvotes: 1

Related Questions