[英]Merge two Arraylist & retains all the value in Java
我有2 arrayList
的PresentErrorList
& PastErrorList
兩者都具有3個字段errorCode
, presentErrorCount
& pastErrorCount
。
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
}
因此,在添加元素之后,這是完成的操作:
List
流完成 Map
:(對象的代碼,對象) key
,我告訴它添加一個具有上一個和新添加的總和的新Object values
生成一個List
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.