-3

I think i misunderstood the application of HashMap when i was rewriting parts of my code to make it more maintainable.

joints is a HashMap containing a set of objects identified by a String:

private HashMap<String, SomeObject> joints = new HashMap(5, 1);

Population of the HashMap is straightforward enough via the put() method. However I now need to run a method on each of them. The below code produces a syntax error at the first period, but i believe it illustrates what I am trying to do.

joints.("knee").someMethod(someValue);
joints.("hip").someMethod(someOtherValue);
joints.("shoulder").someMethod(someOtherValue);
joints.("neck").someMethod(someOtherValue);
joints.("elbow").someMethod(someOtherValue);

What would be a valid/correct equivalent? of the above? I am thinking get() the object, delete it from the map, modify the object, put() it back into the HashMap.

While a foreach would be a step closer, this is a moot approach as the arguements for someMethod() are different for each object.

Jarmund
  • 3,003
  • 4
  • 22
  • 45
  • possible duplicate of [How do I use a foreach loop in Java to loop through the values in a HashMap?](http://stackoverflow.com/questions/448122/how-do-i-use-a-foreach-loop-in-java-to-loop-through-the-values-in-a-hashmap) – DavidPostill Aug 16 '14 at 11:07
  • @DavidPostill not as far as i can see. The second question is related, but the first one is not a duplicate, as this is more of a question about syntax – Jarmund Aug 16 '14 at 11:08
  • 2
    Read the manual. http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html HINT: The method is named `.get(Object)` – Unihedron Aug 16 '14 at 11:19
  • @Unihedron I concluded that it wasn't the one, as I believed that would modify a copy of the object, rather than the object in the HashMap, but it works contrary to my intuition – Jarmund Aug 16 '14 at 11:32

3 Answers3

2

To access a specific value in a Map (as opposed to looping over them all), use the get method.

joints.get("knee").someMethod(someValue);
user253751
  • 57,427
  • 7
  • 48
  • 90
2

A nice way might be to use a generic method.

First, define an interface with your method that is common to all values in the map:

public interface SomeInterface {

    public void someMethod();

}

Then, you can iterate over your map and call the common method for each value:

public <T extends SomeInterface> void callMethodOnValues(Map<String, T> map) {
    for (T value : map.values()) {
       value.someMethod();
    }
}
Josh
  • 697
  • 6
  • 21
0

If the value retrieved from the key is an instance of a class that implements someMethod() then it would be like this:

for(String key: joints.keySet())
{
   someObject obj = joints.get(key);
   obj.someMethod(value);
}
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22