You too, are suffering from object denial.
String
is not a good type for handling numbers or dates. For a number I'd use int
(if you only have integer values), double
or BigDecimal
(if it's a monetary ammount or some other exact decimal number).
For the date I'd use either a Date
/Calendar
or LocalDate
from Joda Time (if you can use an external library).
Obviously this means that you can no longer store your data in a String[]
, but that's not really an appropriate type for any kind of structured data, anyway.
You'd want to write a class that reflects what your values are about:
public class DatedValue {
private final Date date;
private final BigDecimal value;
public DatedValue(final Date date, final BigDecimal value) {
this.date = date;
this.value = value;
}
public Date getDate() {
return date;
}
public BigDecimal getValue() {
return value;
}
}
Then you can simply create the new values by iterating over the original ArrayList<DatedValue>
:
Map<Date,DatedValue> result = new LinkedHashMap<Date,DatedValue>();
for(DatedValue dv : datedValues) {
DatedValue newDV = result.get(dv.getDate());
if (newDV == null) {
newDV = dv;
} else {
newDV = new DatedValue(dv.getDate(), dv.getValue().add(newDV.getValue()));
}
result.put(dv.getDate(), newDV);
}
List<DatedValue> sums = new ArrayList<DatedValue>(result.values());