I have an ArrayList containing Objects that have a date value.
Now I want to manage to create a new ArrayList for each year that contains all the Objects from the main ArrayList that have the same year in their date Value.
So all Objects from 2010 go in one List, all from 1999 in another.
You need a
Map<Year,List<DatedObject>>, maybe evenSortedMaplike aTreeMap.You can also use multimap from Guava.
Essentially you map from each year (perhaps just an
Integer), theList<DatedObject>that belong in that year.And since years have a natural sorting order, you may want to see if
SortedMapprovides you with functionalities that you need. Most likely the answer is yes.The Map Example
Here’s a snippet in Java that shows you how you can populate the map. Note also that
NavigableMapis used instead ofSortedMap;NavigableMapallows inclusive range queries (see related question).Related questions
The Partitioned List
If you absolutely insists on a
List<List<DatedObject>> partitionedList, then build the map as above, and simply follow it with:The MultiMap Example
You can also use
Multimapfrom Guava, andMultimaps.indexutility method as follows:API Links
com.google.common.collect.Multimapcom.google.common.collect.Multimapscom.google.common.base.Function