Java displays data from two arrays and inserts into a third array

I am having a hard time matching the data in the two lists in the third list. My sample data is as follows:

Categorylist ID:  1,2,3,4,5,6,7,8,9,10,42,46,49,50
CurrentMonthByCat ID: 1,2,3,4,5,6,7,8,9,10,42,49,50
(the transaction amount value for CurrentMonthByCat: 92,46,40,180,60,10,1510,200,500,10,234,12)

      

There is no 46 in currentMonthByCat. I am trying to do it in such a way that if the current MonthByCat ID does not exist from the ID of the category list, I insert 0 into the third list rather than getting the transaction amount from CurrentMonthByCat and insert it into the third list.

ArrayList<Double> total = new ArrayList<Double>();

    for(int i = 0; i < categorylist.size(); i++){
        for(int j = 0; j < currentMonthByCat.size(); j++){
            if(categorylist.get(i).getCategoryID().equals(currentMonthByCat.get(j).getCategory().getCategoryID())){
                Log.d("IIIII", categorylist.get(i).getCategoryID());
                Log.d("JJJJJ", currentMonthByCat.get(j).getCategory().getCategoryID());
                total.add((double)currentMonthByCat.get(j).getTransactionAmt());
            }else{
                total.add(0.0);
            }
        }
    }

    for(int k = 0; k < total.size(); k++){
        Log.d("KKKKK", String.valueOf(total.get(k)));
    }

      

But the printed result of the general list is:

  92,0,0,0,0,0,0,0,0,0,0,0,0,0,46,0,0,0...

      

I expected:

  92,46,40,180,60,10,1510,200,500,10,0,234,12

      

I wanted to insert 0 only if the ID in currentMonthByCat doesn't match the ID in the category list. For example, identifier 46, which is the third position from the right.

I figured out that the reason is that, firstly, I inserted 92 into the third array, then the category list ID is still 1, then it will compare against all others in currentMonthByCat before going to ID 2. That's why unnecessary zeros. But I'm not sure how to actually sort it to achieve what I wanted.

Any ideas?

Thanks in advance.

+3


source to share


3 answers


It's easy. you cannot decide whether to add zero or a value to the shared array unless the inner loop ends. so maybe you add existAtIndex element and initialize it with -1 and in the loop if you find the element then assign existAtIndex to the index and break the loop, or if it doesn't exist you add zero. so the code will be something like this:

ArrayList<Double> total = new ArrayList<Double>();
int existAtIndex;
    for(int i = 0; i < categorylist.size(); i++){
        // search for the element index
        existAtIndex = -1;
        for(int j = 0; j < currentMonthByCat.size(); j++){
            if(categorylist.get(i).getCategoryID().equals(currentMonthByCat.get(j).getCategory().getCategoryID())){

                existAtIndex = j;
                break;
            }
        }

        // add the value in the element index or add zero if the element not exist
        if (existAtIndex != -1) {
          total.add((double)currentMonthByCat.get(existAtIndex).getTransactionAmt());
        }
        else {
            total.add(0.0);
        }
    }

    for(int k = 0; k < total.size(); k++){
        Log.d(String.valueOf(total.get(k)));
    }

      



For the best code you can use, there is a method to check if an element exists or not in arrayList, instead of using a basic loop. Good luck.

0


source


Put your values ​​in Map<Integer, Double>

Map<Integer, Double> map = new HashMap<Integer, Double>();
for (int i = 0; i < currentMonthByCat.size(); ++i) {
    //... categoryId = currentMonthByCat.get(i).categoryId
    //... amount = currentMonthByCat.get(i).amount
    map.put(categoryId, amount);
}

      

Then navigate the map using the values ​​from the category list ID:

// create result arraylist
ArrayList<Double> total = new ArrayList<Double>();
for (int i = 0; i < categorylist.size(); ++i) {
    Double amount = map.get(categorylist.get(i));
    if (amount == null) {
        total.add(0.0);
    } else {
        total.add(amount);
    }
}

      



The list of results total

will contain sums for existing matches or zeros for nonexistent ones.

Alternative way If guaranteed, the list of categories is sorted and CurrentMonthByCat is sorted

you can traverse one of the lists by storing the pointer / cursor in another list and not iterating over the other list from the beginning, but from the previously remembered cursor value, resulting in better average performance than n ^ 2

+1


source


You have a lot of code for what you are trying to do here. I think the following snippet does what you want in a very readable and maintainable way.

    //First of all we are interested in getting a transaction amount for each value in currentMonthByCat
    //so loop around using your object (not sure what it called)
    for(CurrentMonth value : currentMonthByCat){
        //check if it present. 
        //We create a new method here that gets you your category list as a list of integers. 
        //This is key to making the whole method much more readable.
        if(categorylist.getIdsAsList().contains(value.getCategory().getCategoryID())){
            //it is so add it
            total.add(value.getTransactionAmt());
        } else {
            //it not so add a 0
            total.add(0.0);
        }
    }

      

The getIdsAsList method might look like this:

public List<Integer> getIdsAsList(){
    List<Integer> result = new ArrayList<>();
    for (CategoryListItem item : categorylist) {
        result.add(item.getCategoryId());
    }
    return result;
}

      

+1


source







All Articles