1

Having a object that has 3 properties:

Item
    String date;
    int value1;
    int value2;

I have first ArrayList<Item> listA which contains:

2017-01-18, 0, 0
2017-01-17, 0, 0
2017-01-16, 0, 0
2017-01-15, 0, 0

Second ArrayList<Item> listB which contains:

2017-01-18, 7, 3
2017-01-15, 4, 0

I want to combine both lists, into a final one, having the values summed by same date

2017-01-18, 7, 3
2017-01-17, 0, 0
2017-01-16, 0, 0
2017-01-15, 4, 0
Alin
  • 14,809
  • 40
  • 129
  • 218
  • Combine them both with `addAll()` then just implement the `Comparable` interface with your logic to sort by date, then `Collections.sort(yourCombinedList)`, or create a Implentation of the `Comparator` interface - http://stackoverflow.com/a/14452176/4252352 – Mark Jan 18 '17 at 17:59
  • The main issue for me is adding the value1 and value2 for same date – Alin Jan 18 '17 at 18:02
  • I see - misunderstood, you want to aggregate duplicate dates – Mark Jan 18 '17 at 18:07

2 Answers2

0

Try this:

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
            }
        }
    }
}

happy coding!

Leandro Borges Ferreira
  • 12,422
  • 10
  • 53
  • 73
0

try this

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);
    }
}

and your item class be like

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;
    }
}
Rajesh Gosemath
  • 1,812
  • 1
  • 17
  • 31