Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Object attribute while iterating over HashMap

I am using a HashMap where the key is String and Value is an object (Signal). While iterating over the Map Can I edit one of the attributes of my object before I write it to a file.

Here is my code

public void createFile(HashMap<String , Signal> map, final BufferedWriter buffwriter, long totalSize) {
    final Iterator<String> iterator = map.keySet().iterator();
    while(iterator.hasNext()) {
       String messageName = iterator.next();
       Signal signal  = map.get(messageName);
       signal.setBandwidth((signal.getSize()/totalSize)*100);
       csvOutput.write(signal.getSource());
       csvOutput.write(signal.getName());
       csvOutput.write(signal.getComponent());
       csvOutput.write(Integer.toString(signal.getOccurance()));
       csvOutput.write(Integer.toString(signal.getSize()) );
       csvOutput.write(Float.toString(signal.getBandwidth()));
       csvOutput.endRecord();               
    }
 }

Signal.java

  public class Signal implements Comparable<Signal>{    
      String name;
      float bandwidth;

      public void setName(String name){
       this.name = name;
   }
      public void setBandwidth(float bandwidth){
       this.bandwidth  = bandwidth;
   }

       public String getName(){
       return this.name;
   }

       public float getBandwidth(){
       return this.bandwidth;
   }
        @Override
   public int compareTo(Signal signal) {
       return 1;
   }

In the above piece of code I use messagName as key for each key in the map I get its value Try to set the bandwidth attribute and then write it to file, but it is not updating the bandwidth.

How can I do it ? Is the only option I am left with to remove the Entry and add another with new value while iterating ?

Thanks In Advance

like image 545
Wearybands Avatar asked Dec 11 '25 05:12

Wearybands


1 Answers

Let me guess, your bandwidth stays 0? That's because of the way you calculate it. I assume that getSize() returns an int/long, and totalSize is an int/long. This results in the result of your calculation

(signal.getSize()/totalSize)*100

being an int as well. Try the following:

(signal.getSize() / (float) totalSize) * 100

Now one of the operands is a float, what makes the result of the calculation a float as well. Hope this resolves your problem.

See also here.

like image 168
Sven Amann Avatar answered Dec 12 '25 19:12

Sven Amann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!