我有一个年份的整数数组及其对应的值,看起来像下面的代码

int[] earningYear = {2012,2013,2014};
int[] earningAmount = {100,150,120};
int[] expenseYear = {2012,2014};
int[] expenseAmount = {50,30};


我想从对应于年份的profitAmount中减去expenseAmount,并且输出列表应如下所示

int[] savingsYear = {2012,2013,2014};
int[] savingsamount = {50,150,90};


请帮助我这样做。提前致谢

最佳答案

@ umair.ali和@Casper给出的答案很好,将数组转换为Maps是可行的方法。
我建议使用TreeMap(或SortMap接口的其他实现)。默认情况下,TreeMap对其键按升序排序。这样,如果您确实希望节省大量费用,则在处理后不必进行任何麻烦的地图排序。

这是完整的示例:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class SavingsApp {

    public Map<Integer, Integer> arraysToMap(int[] years, int[] money) {
        Map<Integer, Integer> newMap = new HashMap<Integer, Integer>();
        if (years == null || money == null || years.length != money.length) {
            throw new IllegalArgumentException();
        }
        for (int i=0; i< years.length; i++ ) {
            newMap.put(years[i], money[i]);
        }

        return newMap;
    }

    public Map<Integer, Integer> calculateSavings(Map<Integer, Integer> earningsMap, Map<Integer, Integer>expensesMap) {
        Map<Integer, Integer> savingsMap = new TreeMap<Integer, Integer>();
        savingsMap.putAll(earningsMap);

        for (Entry<Integer, Integer> expensePerYear : expensesMap.entrySet()) {
            Integer year = expensePerYear.getKey();
            Integer expense = expensePerYear.getValue();

            Integer earning = savingsMap.get(year);
            if (earning == null) {
                earning = 0;
            }
            savingsMap.put(year, earning-expense);
        }
        return savingsMap;
    }


    public static void main(String[] args) {
        int[] earningYear = {2012,2013,2014};
        int[] earningAmount = {100,150,120};
        int[] expenseYear = {2012,2014};
        int[] expenseAmount = {50,30};

        SavingsApp app = new SavingsApp();

        // convert arrays to maps
        Map<Integer, Integer> earningsMap = app.arraysToMap(earningYear, earningAmount);
        Map<Integer, Integer> expensesMap = app.arraysToMap(expenseYear, expenseAmount);

        // compute savings per year
        Map<Integer, Integer> savingsMap = app.calculateSavings(earningsMap, expensesMap);

        // convert result map to array
        List<Integer> savingsList = new ArrayList<Integer>(savingsMap.values());
        Integer[] savingsArray = new Integer[savingsList.size()];
        savingsList.toArray(savingsArray);
    }
}


要注意的一件事是savingsArray将是Integer[]类型而不是int[]

10-04 20:33