0

I'm attempting to access values that are held inside a Class which is listed in a HashMap.

In my first class I create a HashMap which links to the "LiftingStats" class.

Map<String, LiftingStats> fitnessGoals = new HashMap<String, LiftingStats>();

In the LiftingStats class I do the following...

public class LiftingStats
{
   public String activity;
   public String weightType;
   public int weight;
   public double difficulty;

   /**
    * Constructor for objects of class LiftingStats
    */
   public LiftingStats()
   {
      this.run();
   }

   /**
    * test method to fill values
    */
   public void run(){
      //code
      this.activity = "bench press";
      this.weightType = "Kg";
      this.weight = 100;
      this.difficulty = 8.5;
   }

I'm running a test method to fill the hashmap with some values

   public void testMethod(){
      fitness.put("activityone", new LiftingStats());
      fitness.put("activitytwo", new LiftingStats());

4 Answers4

2

There are many ways to access them.

For retrieving the value of a specific key entry

LiftingStats valueForOne = fitness.get("activityone");

For retrieving values without concern for keys

Collection<LiftingStats> values = fitness.values();

For retrieving key and value pairs

Set<Map.Entry<String, LiftingStats>> entries = fitness.entrySet();
for (Map.Entry<String, LiftingStats> entry : entries) {
   entry.getValue();
}

or some variant.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
1

A Map is a Data Structure consisting of Key, Value pairs. In this case you have two keys that reference two instances of LiftingStats objects. To access these objects simply use your specific key to retrieve the object(s). Ex:

LiftingStats current = fitness.get("activityone");

With your reference to current you can perform operations on that specific LiftingStats object.

Similarly, you can 'daisy-chain' function calls together like this and still mutate the object within the Map. Ex:

fitness.get("activityone").someMethod();
andrewdleach
  • 2,458
  • 2
  • 17
  • 25
1

You can adapt this answer to your problem : How to efficiently iterate over each Entry in a Map?

Map<String, LiftingStats> fitnessGoals = new HashMap<String, LiftingStats>();
for (Map.Entry<String, LiftingStats> entry : fitnessGoals.entrySet())
{
    //What you need to do with your map
}
Community
  • 1
  • 1
Laurent-P
  • 145
  • 1
  • 9
0

Another way by which you can access variables of an object in HashMap is by typecasting the data fetched by getValue() method of a Hashmap into the user defined class.

You can use the following code:

Map<String, LiftingStats> lstats= new HashMap<String, LiftingStats>();
for (Map.Entry ls:lstats.entrySet()) {
    System.out.println(ls.getKey()+" "+((LiftingStats)ls.getValue()).activity);
}

Any variable present in the class can be accessed simply by using ((LiftingStats)ls.getValue()).Var_name . where Var_name is the name of any class variable.