簡體   English   中英

合並兩個Arraylist並保留Java中的所有值

[英]Merge two Arraylist & retains all the value in Java

我有2 arrayListPresentErrorListPastErrorList兩者都具有3個字段errorCodepresentErrorCountpastErrorCount

presentErrorList

[errorCode=1000,presentErrorCount=10,pastErrorCount =0]
[errorCode=1100,presentErrorCount=2,pastErrorCount =0]

pastErrorList

[errorCode=1003,presentErrorCount=0,pastErrorCount =10]
[errorCode=1104,presentErrorCount=0,pastErrorCount =12]
[errorCode=1000,presentErrorCount=0,pastErrorCount =12]

在為Present計算時,pastErrorCount = 0,反之亦然。 我的finalArrayList應該是

[errorCode=1000,presentErrorCount=10,**pastErrorCount =12**]
[errorCode=1100,presentErrorCount=2,pastErrorCount =0]
[errorCode=1003,presentErrorCount=0,pastErrorCount =10]
[errorCode=1104,presentErrorCount=0,pastErrorCount =12]`

正如您在errorCode=1000的最終列表中所看到的,因為它過去是重復的,所以只有1個對象同時具有當前和過去的錯誤計數。

因此,要找到一種方法並不容易,但最終目的是我要做的:

public static void main(String[] args) {
    List<ErrorCodeModel> presentErrorList = new ArrayList<>();
    presentErrorList.add(new ErrorCodeModel("1000", 10, 0));
    presentErrorList.add(new ErrorCodeModel("1100", 2, 0));

    List<ErrorCodeModel> pastErrorList = new ArrayList<>();
    pastErrorList.add(new ErrorCodeModel("1003", 0, 10));
    pastErrorList.add(new ErrorCodeModel("1104", 0, 12));
    pastErrorList.add(new ErrorCodeModel("1000", 0, 12));

    Map<String, ErrorCodeModel> map = Stream.of(presentErrorList, pastErrorList)
                .flatMap(Collection::stream)
                .collect(Collectors.toMap(ErrorCodeModel::getErrorCode,
                      Function.identity(),
                      (oldValue, newValue)
                      -> new ErrorCodeModel(oldValue.getErrorCode(),
                           oldValue.getPresentErrorCount()+newValue.getPresentErrorCount(),
                           oldValue.getPastErrorCount()+newValue.getPastErrorCount())));

    List<ErrorCodeModel> errorList = new ArrayList<>(map.values());

    errorList.sort((err1, err2) //line 20*
                -> Integer.compare(Integer.parseInt(err1.getErrorCode()),
                                   Integer.parseInt(err2.getErrorCode())));

    System.out.println(errorList.toString());

    //*line 20 : Optionnal, if you want to sort by errorCode
    //(need to parse to int to avoir alphabetical order
}

因此,在添加元素之后,這是完成的操作:

  • 每個2 List流完成
  • 目標是將它們添加到Map :(對象的代碼,對象)
  • 使用(oldValue,newValue)lambda-exp是始終在地圖中的key ,我告訴它添加一個具有上一個和新添加的總和的新Object
  • 映射后,將根據您要求的表示ErrorCodeModel的values生成一個List

暫無
暫無

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

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