Search code examples
javaperformanceprocessing-efficiencycode-complexity

Which is the fastet and the most efficient implementation in java for updating object in a list if present, else add it


I have a problem statement which is working but still i would like to know more efficient, faster and more importantly correctly designed to handle the below mentioned scenario.

I have a POJO class

class A {
  String s;
  Double d;
}

I am trying to populate a List, basically a List of Object A into the list. Now the implementation in question. While adding the Object A into the list i need to check if an Object with String s already exists. If yes i want to update the older Object with old d1 + new d1 and do not add the new Object to the list, If no add the new Object to the list. My present implementation is something like below.

double dd = 0.0;
    List<A> aList = new List<A>();
    List<A> aListToRemove = new List<A>();
    A newA = null;
    for(int i=0;i<=100;i++ ){
        newA = method call which returns newA;
        for(A oldA: aList ){
            if(oldA.getS().equals(newA.getS())){
                dd = oldA.getD() + newA.getD();
                newA.setD(dd);
                aListToRemove.add(oldA);
            }
            aList.add(newA);
            aList.removeAll(aListToRemove);
        }
    }

//at the end, i would like to see aList with no duplicates, but with updated d value.

Is there a more efficient way to do the processing within the second for loop?


Solution

  • It seems you could use a map for your use case:

    Map<String, A> map = new HashMap<> ();
    

    and put items in the map like this:

    map.put(someA.s, someA);
    

    That should turn your O(n^2) algoritm into an O(n) algorithm.

    When you receive a newA, you can use the following:

    A a = map.get(newA.getS());
    if (a == null) {
        map.put(newA.getS(), newA); //new string => new item in the map
    } else {
        a.setD(a.getD() + newA.getD()); //found string => updating the existing item
    }