拥有一个具有3个属性的对象:
Item
String date;
int value1;
int value2;
我有第一个ArrayList<Item>
listA,其中包含:
2017-01-18, 0, 0
2017-01-17, 0, 0
2017-01-16, 0, 0
2017-01-15, 0, 0
第二个ArrayList<Item>
listB包含:
2017-01-18, 7, 3
2017-01-15, 4, 0
我想将两个列表组合成一个最终的列表,其值与相同的日期相加
2017-01-18, 7, 3
2017-01-17, 0, 0
2017-01-16, 0, 0
2017-01-15, 4, 0
答案 0 :(得分:0)
试试这个:
public static void sumList(List<Item> list1, List<Item> list2){
List<Item> bigger;
List<Item> smaller;
if(list1.size() > list2.size()){
bigger = list1;
smaller = list2;
} else{
bigger = list2;
smaller = list1;
}
for(int i = 0; i < bigger.size(); i++){
for(int j = 0; j < smaller.size(); j++){
if(bigger.get(i).date.equals(smaller.get(j).date)){
bigger.get(i).value1 = bigger.get(i).value1 + smaller.get(j).value1
bigger.get(i).value2 = bigger.get(i).value2 + smaller.get(j).value2
}
}
}
}
快乐的编码!
答案 1 :(得分:0)
试试这个
List<Item> firstList = new ArrayList<Item>();
List<Item> secondList = new ArrayList<Item>();
HashMap<String, Item> hashMap = new HashMap<String, Item>();
for(Item item: firstList) {
hashMap.put(item.date, item);
}
for(Item item: secondList) {
Item tempItem = hashMap.get(item.date);
if(tempItem != null) {
tempItem.add(item);
hashMap.put(tempItem.date, tempItem);
} else {
hashMap.put(item.date, item);
}
}
你的项目类似
class Item {
String date;
int value1;
int value2;
public void add(Item item) {
this.value1 = this.value1 + item.value1;
this.value2 = this.value2 + item.value2;
}
}