简体   繁体   English

Java映射两个数组中的数据并将其插入第三个数组

[英]Java mapping data from two arrays and insert into third array

I am having difficulty mapping the data in two lists into a 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 a missing 46 in the currentMonthByCat. currentMonthByCat中缺少46个。 I am trying to do it in a way such that if the currentMonthByCat ID does not exist from the categorylist ID, I will insert 0 into the third list rather than getting the transaction amount from CurrentMonthByCat and push it into the third list. 我正在尝试以某种方式做到这一点,如果在类别列表ID中不存在currentMonthByCat ID,我将在第三个列表中插入0,而不是从CurrentMonthByCat获取交易金额并将其推入第三个列表。

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 out result of total list is: 但是总列表的打印结果是:

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

What I expected is: 我所期望的是:

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

I wanted to insert 0 only if the ID in currentMonthByCat does not match the ID in categorylist. 我只想在currentMonthByCat中的ID与categorylist中的ID不匹配时插入0。 For instance, the ID 46 which is the 3rd position from the right. 例如,ID 46,它是从右数第3个位置。

I realized the reason is because firstly I inserted 92 into third array, then the categorylist ID is still at 1, then it will compare with all the rest in the currentMonthByCat before moving to ID 2. That is why the unnecessary zeros. 我意识到原因是因为首先我在第三个数组中插入了92,然后类别列表ID仍为1,然后它将与currentMonthByCat中的所有其余内容进行比较,然后再移至ID2。这就是为什么不必要的零。 But I not sure how to actually sort it to achieve what I wanted. 但是我不确定如何对它进行排序以实现我想要的。

Any ideas? 有任何想法吗?

Thanks in advance. 提前致谢。

Put your values into Map<Integer, Double> 将您的值放入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 traverse the map using values from Categorylist ID: 然后使用Categorylist 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 result list total will contain amounts for existing mappings, or zeros for non-existent. 结果列表total将包含现有映射的数量,或不包含零的数量。

Other way If it is guaranteed categorylist is sorted and CurrentMonthByCat is sorted 其他方法如果可以保证categorylist被排序并且CurrentMonthByCat被排序

you can then traverse one of the lists while keeping index/cursor to the other list and not iterating the other list from the beginning, but from previously remembered cursor value, resulting in better average performance than n^2 然后,您可以遍历列表中的一个,同时保持索引/光标到另一个列表,而不是从头开始迭代另一个列表,而是从以前记住的游标值开始迭代,从而获得比n ^ 2更好的平均性能

It's easy one. 这很简单。 you can't take a decision of adding zero or value in the total array unless the inner loop finish. 除非内部循环完成,否则您无法决定在总数组中添加零或值。 so probably you add element existAtIndex and initialize it with -1 and in the loop if you find the element then assign the index to existAtIndex and break the loop or if it's not exist then you add zero. 所以可能您添加了元素existAtIndex并用-1对其进行了初始化,如果找到该元素,然后将索引分配给existAtIndex并中断了循环,或者如果不存在则添加零。 so the code will be something like : 因此代码将类似于:

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 better code you could use contains method to check for the item if exist or not in arrayList instead of using the basic loop. 为了获得更好的代码,您可以使用contains方法检查是否在arrayList中存在该项目,而不是使用基本循环。 Good luck 祝好运

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's called)
    for(CurrentMonth value : currentMonthByCat){
        //check if it's 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's not so add a 0
            total.add(0.0);
        }
    }

The getIdsAsList method could look like this: getIdsAsList方法如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM