1、功能介绍:
将List中每个map元素中的指定字段,比如RESOURCE_TYPE字段的值相同的元素中的X_USED_VALUE的值想加,并返回合并后的list数据
List实例:
[
{
"X_USED_VALUE": "123",
"ADDUP_ITEM_NAME": "abc",
"FREE_RES_TYPE": "01",
"RESOURCE_TYPE": "S1"
},
{
"X_USED_VALUE": "0",
"ADDUP_ITEM_NAME": "abc)",
"FREE_RES_TYPE": "01",
"RESOURCE_TYPE": "S2"
},
{
"X_USED_VALUE": "123",
"ADDUP_ITEM_NAME": "abc",
"FREE_RES_TYPE": "01",
"RESOURCE_TYPE": "S1"
},
{
"X_USED_VALUE": "456",
"ADDUP_ITEM_NAME": "abc",
"FREE_RES_TYPE": "01",
"RESOURCE_TYPE": "S2"
}
]
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SumXUsedValueWithMoreConditions {
public static List<Map<String, String>> processData(List<Map<String, String>> dataList) {
Map<String, Map<String, String>> sumMap = new HashMap<>();
for (Map<String, String> item : dataList) {
String key = item.get("RESOURCE_TYPE") + "_" + item.get("ADDUP_ITEM_NAME");
String xUsedValue = item.get("X_USED_VALUE");
if (!"0".equals(xUsedValue)) {
if (!sumMap.containsKey(key)) {
sumMap.put(key, new HashMap<>(item));
} else {
Map<String, String> existingItem = sumMap.get(key);
int currentValue = Integer.parseInt(existingItem.get("X_USED_VALUE"));
int newValue = Integer.parseInt(xUsedValue);
existingItem.put("X_USED_VALUE", String.valueOf(currentValue + newValue));
}
}
}
List<Map<String, String>> result = new ArrayList<>();
result.addAll(sumMap.values());
return result;
}
public static void main(String[] args) {
List<Map<String, String>> dataList = new ArrayList<>();
Map<String, String> item1 = new HashMap<>();
item1.put("X_USED_VALUE", "123");
item1.put("ADDUP_ITEM_NAME", "abc");
item1.put("FREE_RES_TYPE", "01");
item1.put("RESOURCE_TYPE", "S1");
Map<String, String> item2 = new HashMap<>();
item2.put("X_USED_VALUE", "0");
item2.put("ADDUP_ITEM_NAME", "abc");
item2.put("FREE_RES_TYPE", "01");
item2.put("RESOURCE_TYPE", "S2");
Map<String, String> item3 = new HashMap<>();
item3.put("X_USED_VALUE", "123");
item3.put("ADDUP_ITEM_NAME", "abc");
item3.put("FREE_RES_TYPE", "01");
item3.put("RESOURCE_TYPE", "S1");
Map<String, String> item4 = new HashMap<>();
item4.put("X_USED_VALUE", "456");
item4.put("ADDUP_ITEM_NAME", "abc");
item4.put("FREE_RES_TYPE", "01");
item4.put("RESOURCE_TYPE", "S2");
dataList.add(item1);
dataList.add(item2);
dataList.add(item3);
dataList.add(item4);
List<Map<String, String>> processedList = processData(dataList);
for (Map<String, String> processedItem : processedList) {
System.out.println(processedItem);
}
}
}
运行后截图: