How to efficiently get the values from a HashMap with a static class?

167 views Asked by At

I have a class with a HashMap<k,v>. The type of the values of this HashMap is a static class which has two different objects as attributes. i.e.,

   public class Example {
      private HashMap<String, StaticClassExample> map;
      private static class StaticClassExample {
           private Object1 o1;
           private Object2 o2;
           //...   
      }
      //...
   }

And my question is how can I do this operation efficiently:

   public List<Object1> getAllObject1() {}

I know that I can do: map.values() and then iterate the values collection and get Object1 from each StaticClassExample, but this wouldn't be efficient. It's possible what I ask or I must create another hashmap for my purpose?

1

There are 1 answers

1
esaj On

If you don't mind some memory overhead, you could keep a separate list with the o1-values:

public class HashMapList
{
    private HashMap<String, StaticClassExample> map = new HashMap<String, HashMapList.StaticClassExample>();

    private List<Object> o1List = new LinkedList<Object>();

    public static class StaticClassExample
    {
        private Object o1;
        private Object o2;
    }

    public void addStaticClassExample(String key, StaticClassExample example)
    {
        StaticClassExample oldVal = map.put(key, example);
        if(oldVal != null)
        {
            o1List.remove(oldVal.o1);
        }
        o1List.add(example.o1);
    }

    public StaticClassExample getStaticClassExampleByKey(String key)
    {
        return map.get(key);
    }

    public void removeStaticClassExampleByKey(String key)
    {
        StaticClassExample removed = map.remove(key);
        if(removed != null)
        {
            o1List.remove(removed.o1);
        }
    }

    public List<Object> getAllObject1()
    {
        return Collections.unmodifiableList(o1List);
    }   

}

Of course, this requires you to encapsule the HashMap inside the class and never give a straight access to it, because then someone using the class could modify the HashMap directly, and the List would no longer be in sync with the Map. Note that getAllObject1 returns an unmodifiable view of the internal list, so it can't be modified from outside of the class.