0

I have e.g. following Lists:

List<tst> listx; // tst object has properties: year, A, B, C, D year A B C D ------------ 2013 5 0 0 0 // list1 2014 3 0 0 0 2013 0 8 0 0 // list2 2014 0 1 0 0 2013 0 0 2 0 // list3 2014 0 0 3 0 2013 0 0 0 1 // list4 2014 0 0 0 5 

if I use addAll method, the listTotal will be:

year A B C D ------------ 2013 5 0 0 0 // listTotal 2014 3 0 0 0 2013 0 8 0 0 2014 0 1 0 0 2013 0 0 2 0 2014 0 0 3 0 2013 0 0 0 1 2014 0 0 0 5 

How to merge them to the listRequired which would be like this?

year A B C D ------------ 2013 5 8 2 1 // listRequired 2014 3 1 3 5 

3 Answers 3

4

Use a Map<Integer, Tst> containing, for each year (the key of the map) the Tst you want for this year as a result.

Iterate through your listTotal and, for each Tst:

  • if the year of the Tst isn't in the map yet, then store the Tst for this year
  • else, get the Tst from the map and merge it with the current Tst

In the end, the values() of the map is what you want in your listRequired.

Code:

Map<Integer, Tst> resultPerYear = new HashMap<>(); for (Tst tst : listTotal) { Tst resultForYear = resultPerYear.get(tst.getYear()); if (resultForYear == null) { resultPerYear.put(tst.getYear(), tst); } else { resultForYear.merge(tst); } } Set<Tst> result = resultPerYear.values(); 
Sign up to request clarification or add additional context in comments.

Comments

0

use a map to maintain a mapping from year to the TST structure.
iterate each item of the lists, retrieve the corresponding TST structure and update the A/B/C/D attributes manually

Comments

0

You should be able to do it by defining a custom merge method:

List<tst> merge (List<tst> listA, List<tst> listB) 

which merges the properties of each element in listA with the element of the same index in listB.

Call this method iteratively on list1, ...list4 to get listRequired.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.