I have a case where I need to aggregate a list of Beans/Objects to display their total characteristics. Let me explain my requirement first. I have a List of person details as shown :
Person Bank Balance
---------------------
Sam GS 200
Sam JP 200
Sam WF 200
John GS 200
John JP 200
Robin JP 200
Robin JP 200
I want to aggregate the balances per person.
Sam 700 <---- Key
------------------
Sam GS 200
Sam JP 300
Sam WF 200
John 500 <---- Key
------------------
John GS 300
John JP 200
Robin 200 <---- Key
------------------
Robin JP 100
Robin JP 100
Now, let's switch to what I have in my code - a List of such objects and I need to put them in a Map. The key would be the aggregated details, and its value will be the list of details. Here's my attempt, although its not that great:
public Map<Bean, List<Bean>> getAggregation(List<Bean> beans)
{
Map<Bean, ArrayList<Bean>> aggreagtedBeans = new HashMap<Bean, new ArrayList<Bean>>();
for(Bean bean : beans)
{
String name = bean.getName();
boolean presentALready = false;
Bean correspondingKey = null;
for(Bean key :aggreagtedBeans.keySet())
{
if(key.getName().equals(name))
{
presentALready = true;
correspondingKey = key;
}
}
if(presentALready)
{
aggreagtedBeans.put(correspondingKey, aggreagtedBeans.get(correspondingKey).add(bean));
}
else
{
aggreagtedBeans.put(bean, aggreagtedBeans.get(correspondingKey).add(bean));
}
}
return aggreagtedBeans;
}
Problems :
Even with this Map approach, the key gets fixed and so am not able to update the balances as each row is added for a specific person.
Limitations :
I know this type of use case is ideal for database order by clauses, but I cannot use them. These are Java Objects.
Also, if you think that I should use a different data structure as per my use case, please suggest so, and if possible please provide a code snippet.
EDIT :
Attaching the Bean class code for reference :
public class Bean
{
String name;
String bank;
int balance;
// constructors and getters
}