[英]Sum Array values of a Firestore field
我無法從 Firestore 文檔字段中對array
值進行求和。
無論我做什么,我都會繼續收到以下錯誤:
java.lang.ClassCastException: java.lang.Long 不能轉換為 java.lang.Integer
我的要求如下:
我有一個 db Collection -> "ALLUSERS" 並且每個文檔 ID 是用戶的電話號碼。
在這個文件下,我有集合“化學”和一個文件“摘要”。 在這方面,我有許多帶有點的章節數組。
我可以通過DocuementSnapshot.get(...thechapter...)獲得這個細節。 但是,一旦我嘗試對數組中的值求和,就會出現上述錯誤。
下面是我試圖用流求和的代碼。
for (DocumentSnapshot document : task.getResult()) {
String phonenumber = document.getString("phonenumb");
students.add(phonenumber);
chemistry.document(phonenumber)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
Map<String, Object> map = task.getResult().getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().contains("chemchaps")) {
List<String> stringList = (List<String>) entry.getValue();
List<Integer> integerList = stringList.stream()
.map(Integer::valueOf).collect(Collectors.toList());
Integer maxValue = Collections.max(integerList);
Toast("Max Value " + integerList + " " + maxValue);
for(int i = 0; i < maxValue; i++){
String chapterNo = "Chapter"+String.valueOf(maxValue);
String chapternumb = "chapter"+String.valueOf(maxValue);
chemistry.document(phonenumber).collection("CHEMISTRY").document("Summary")
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot documentSnapshot = task.getResult();
List<Integer> chaptersum = (List<Integer>) documentSnapshot.get(chapternumb);
long intsum = chaptersum.stream().mapToLong(Integer::longValue).sum();
//chaptersum.stream().reduce(0, (a, b)-> a+b);
//chaptersum.values().stream().mapToInt(Integer::intValue).sum();
Toast("Chapter Nos "+chapterNo + " "+ chaptersum+ " "+ intsum);
}
}
});
}
}
}
Toast("Map data " + map);
}
});
我在這一行收到錯誤:
long intsum = chaptersum.stream().mapToLong(Integer::longValue).sum();
謝謝您的幫助
您收到以下錯誤行:
java.lang.ClassCastException: java.lang.Long 不能轉換為 java.lang.Integer
因為你被添加到chapter1
陣列數字,這基本上存儲為長值,而不是整數。 因此,要解決此問題,請更改以下代碼行:
List<Integer> chaptersum = (List<Integer>) documentSnapshot.get(chapternumb);
long intsum = chaptersum.stream().mapToLong(Integer::longValue).sum();
到
List<Long> chaptersum = (List<Long>) documentSnapshot.get(chapternumb);
long intsum = chaptersum.stream().mapToLong(Long::longValue).sum();
看,列表現在是Long
類型,我們使用 Long 值創建總和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.