這可能是關于 SO 的最簡單的問題,所以首先我道歉,但我無法確定答案,所以我不得不在這里問。
假設你有一個像這樣的流動串列。我想總結 dayId0 的值,然后是 dayId1 并將它們列印在 Room 的上層。例如,dayId0 將繼續為 food_kcal_sum=350 和 dayId1 food_kcal_sum=45。我應該如何為此創建一個回圈?
[
{
"dayId": 0,
"food_kcal": 270.0,
"id": 1
},
{
"dayId": 0,
"food_kcal": 60.0,
"id": 2
},
{
"dayId": 0,
"food_kcal": 20.0,
"id": 3
},
{
"dayId": 1,
"food_kcal": 15.0,
"id": 4
},
{
"dayId": 1,
"food_kcal": 30.0,
"id": 5
}
]
uj5u.com熱心網友回復:
我嘗試使用 Gson。
public class DriverClass {
Map<Integer, Integer> mapValues = new HashMap<>();
public static void main(String[] args) {
Map<Integer, Integer> map = new DriverClass().sumValues();
map.entrySet().forEach(i -> System.out.println(i.getKey() " " i.getValue()));
}
private Map<Integer, Integer> sumValues() {
Gson gson = new Gson();
JsonArray jsonArray = gson.fromJson(myJson(), JsonArray.class);
for (int i = 0; i < jsonArray.size(); i ) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
JsonElement jsonElementDayId = jsonObject.get("dayId");
JsonElement jsonElementFoodCal = jsonObject.get("food_kcal");
calculateValues(jsonElementDayId.getAsInt(), jsonElementFoodCal.getAsInt());
}
return mapValues;
}
private void calculateValues(int jsonElementDayId, int jsonElementFoodCal) {
if (mapValues.containsKey(jsonElementDayId)) {
mapValues.put(jsonElementDayId, mapValues.get(jsonElementDayId) jsonElementFoodCal);
} else {
mapValues.put(jsonElementDayId, jsonElementFoodCal);
}
}
public static String myJson() {
return """
[
{
"dayId": 0,
"food_kcal": 270.0,
"id": 1
},
{
"dayId": 0,
"food_kcal": 60.0,
"id": 2
},
{
"dayId": 0,
"food_kcal": 20.0,
"id": 3
},
{
"dayId": 1,
"food_kcal": 15.0,
"id": 4
},
{
"dayId": 1,
"food_kcal": 30.0,
"id": 5
}
]
""";
}
}
輸出:
0 350
1 45
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432763.html
