Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value without using index in 2D arrayList inside a HashMap, Java

I'm fairly new to ArrayLists anyway but I need them for this simulation project I'm doing so if you guys could help me I would be more than grateful!

I have a HashMap of 2D arrayLists which should be filled with "value" and "time" in every iteration of simulation based on a String key. I define my variable as follow:

protected Map<String, ArrayList<ArrayList<Object>>> history = new HashMap<String,ArrayList<ArrayList<Object>>>();

, and I initialize it like this:

for (String act:keySet)  
   history.put(act, new ArrayList<ArrayList<Object>>());

Every ArrayList of my Map has two arrayList, and in every iteration I should add my "value", and "time" in every arrayList, so I can store my data and its respective time together, but I don't know how to use key, call my arraylist without using index like in normal arrayList when we can do like this:

tmpData.add("foobar"); // Example

Any help would be appreciated.

Vahid

like image 491
vahid khoshdel Avatar asked Mar 05 '26 03:03

vahid khoshdel


1 Answers

protected Map<String, ArrayList<ArrayList<Double>>> history = new HashMap<String,ArrayList<ArrayList<Double>>>();
    Double time=null;
    Double value=null;
    time2=null;
    ArrayList <Double> inner=null;
    for (String act:keySet){
      ArrayList<ArrayList<Double>> outer=null;
      if ((outer=history.get(act))==null)
      {
         outer= new ArrayList<ArrayList<Double>> ();
      }
       inner=new ArrayList <Double>();
       time= value1;//your value for this integer 
       value= value2;
       inner.add(time);
       inner.add(value);
       outer.add(inner);

       history.put(act, outer);
       }

in each iteration we check if the map contains that key, if it does we we add a new we fill the inner ArrayList with new time objecs, and we add it to the preexisted outer ArrayList then we update the value of the outer ArrayList associated with that key, if it doesn't contain that key we create outer map, inner map, and time objects fill the inner ArrayList, outer ArrayList, associate the outer ArrayList with the key.

like image 89
QuakeCore Avatar answered Mar 07 '26 22:03

QuakeCore



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!