| Author |
Group a List<> of objects by their DATE field
|
Chris Boldon
Ranch Hand
Joined: Aug 10, 2006
Posts: 190
|
|
I have a List<> of items that each contain a DATE field.
For the life of me, I cannot figure out how to group them by date.
Say I have 3 objects in my list that have a date of 1-30 and 2 items that have a date of 2-2. I'd like to create a new List that has the DATE and number of obejects that had that date. Using my previous example, it would be 3,1-30 and 2,2-2.
Thanks in advance!
|
 |
Vikas Kapoor
Ranch Hand
Joined: Aug 16, 2007
Posts: 1374
|
|
Chris Boldon wrote:...it would be 3,1-30 and 2,2-2.
Do you want to calculate which date gets repeated how many times?
I am unclear about the question.
|
 |
Richard Walker
Greenhorn
Joined: Feb 20, 2009
Posts: 4
|
|
|
The first thing that springs to mind is to use a Map<DATE,Integer> to hold a count for each DATE. For each object in your List<>, get the count for the DATE out of the Map, and put it back an incremented count.
|
 |
Chris Boldon
Ranch Hand
Joined: Aug 10, 2006
Posts: 190
|
|
Vishal Pandya wrote:
Chris Boldon wrote:...it would be 3,1-30 and 2,2-2.
Do you want to calculate which date gets repeated how many times?
I am unclear about the question.
Sorry about the clarity. Yes, that is exactly what I want.
|
 |
Vikas Kapoor
Ranch Hand
Joined: Aug 16, 2007
Posts: 1374
|
|
You can do something like,
1) Sort your list. (Collections.sort).
2) Compare the list elements(dates) and see how many unique dates are there and their count. (Sorting has made it easy and you can use methods available for List also to do this)
3) Store them into Map<Date,Integer>.
But this all looks very ugly.
What's your purpose behind all this exercise? Provide us more detail.Somebody may suggest you some workaround to achieve the same thing.
|
 |
Chris Boldon
Ranch Hand
Joined: Aug 10, 2006
Posts: 190
|
|
Vishal Pandya wrote:
But this all looks very ugly.
What's your purpose behind all this exercise? Provide us more detail.Somebody may suggest you some workaround to achieve the same thing.
I have List<Hit> and Hit contains a Date (DATETIME format). I am trying to create a graph displaying the number of hits per day. In order to do this, I need to group all of the hits for the same day together.
Normally I'd do this on the database side, but I don't have that luxury.
|
 |
Vikas Kapoor
Ranch Hand
Joined: Aug 16, 2007
Posts: 1374
|
|
|
Ok then you can continue with the above steps.
|
 |
 |
|
|
subject: Group a List<> of objects by their DATE field
|
|
|