簡體   English   中英

對List <>中包含的HashMap <>進行迭代,以獲取Map中包含的數組變量作為Java中的值的附加值

[英]Iteration of HashMap<> included in List<> to get addition of array variables included in map as values in java

我將BankDetails作為pojo對象,並具有以下變量及其getter和setters。

private String bankName;
private  Map<String,Long[]>  monthMap= newHashMap<String,Long[]>();
private String month;

現在我已經創建了List,其中BankDetails的每個bean都存儲在list中,並且在其map中具有多個鍵和值,例如

我有一個豆

map1 = 05, [8,0,0] ;map2 = 06, [6,0,4] ;map3 = 07, [45,3,0] ;map4 = 08, [0,56,9] ;

第二個豆我有

map1 = 05, [0,0,0] ;map2 = 06, [8,0,4] ;map3 = 07, [5,0,1] ;map4 = 08, [2,6,8] ;

...

其中05,06,07和08是個月。

現在我想垂直獲取所有bean中所有map1s map2s map3s和map4s的總和。

現在,我想要的是每月擁有所有列表對象的array元素的grandTotal,並返回List,其中List將只有4個對象,總共四個,如下所示。

map1- 05, [8, 0 ,0] ; map2- 06, [12,0,8] ; map3- 07,[50,3,1] : map4- 08, [2,62,17]

請提出我該怎么做。 在Java中成為newBee確實在迭代和邏輯方面很弱。

您可以執行以下操作:

    // Declare a ArrayList of Map Objects
    ArrayList<Map<String,Long[]>> mapsList = new ArrayList<>();

    // add all the beans
    mapsList.add(monthMap);
    mapsList.add(monthMap2);
    .
    .


    // declare a map for storing the sum
    Map<String,Long[]> sumMap = new HashMap<>();

    // for every key in map (assuming maps have the same amount 
    // of key-value pairs)
    for(String str : mapsList.get(0).keySet()){
        // initialising sum for long arrays
        Long[] sum = {0L,0L,0L};
        // for every map bean
        for (int i = 0; i < mapsList.size(); i++){
            // for every column in long array of map
            for (int j = 0; j < mapsList.get(i).get(str).length; j++) {
                sum[j] += mapsList.get(i).get(str)[j];
            }
        }
        sumMap.put(str,sum);
    }

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM