Is there any solution available to reduce the number of lines of code for the following?
TreeMap<Integer,List<SomeObject>> myMap = new TreeMap<Integer,List<SomeObject>>();
List<SomeObject> list1 = new ArrayList<SomeObject>();
list.add(someObjectInstance1);
list.add(someObjectInstance2);
List<SomeObject> list2 = new ArrayList<SomeObject>();
list.add(someObjectInstance1);
list.add(someObjectInstance2);
List<SomeObject> list3 = new ArrayList<SomeObject>();
list.add(someObjectInstance1);
list.add(someObjectInstance2);
List<SomeObject> list4 = new ArrayList<SomeObject>();
list.add(someObjectInstance1);
list.add(someObjectInstance2);
myMap.put(1, list1);
myMap.put(2, list2);
myMap.put(3, list3);
myMap.put(4, list3);
Assume that SomeObject
represents a custom Date type and List<SomeObject> currentWeek
will represent a list of dates. In this list I will store only starting and ending date of a week. I have to store previous weeks (by subtracting 7 days from the current Sunday and current Saturday) in a map.
The above code will looks good if the loop size is small. What if my loop size is more than 20? Then I tried the following solution.
private Map<Integer, List<SomeObject>> getPreviousWeeks(List<SomeObject> currentWeek) {
TreeMap<Integer,List<SomeObject>> treeMap = new TreeMap<Integer,List<SomeObject>>();
for(int n=0; n<20; n++) {
List<SomeObject> nthWeek = currentWeek;
SomeObject nthWeekStartDate = nthWeek.get(0);
SomeObject nthWeekEndDate = nthWeek.get(1);
nthWeek.clear();
nthWeek.add(nthWeekStartDate);
nthWeek.add(nthWeekEndDate);
treeMap.put(n,nthWeek)
nthWeek.clear();
nthWeekStartDate = nthWeekStartDate.subtractDays(7);
nthWeekEndDate = nthWeekEndDate.subtractDays(7);
nthWeek.add(nthWeekStartDate);
nthWeek.add(nthWeekEndDate);
currentWeek = nthWeek;
}
return treeMap;
}
The problem here is, it is returning 20 days of same day. When I was debugging it is working fine only for the first iteration.
Can any one help me in this?
Thanks.