File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Any easy way to split an Arraylist into multiple lists based on a property of the objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Any easy way to split an Arraylist into multiple lists based on a property of the objects?" Watch "Any easy way to split an Arraylist into multiple lists based on a property of the objects?" New topic
Author

Any easy way to split an Arraylist into multiple lists based on a property of the objects?

forums UseR
Ranch Hand

Joined: Feb 24, 2009
Posts: 169
Hi,

I have an ArrayList of similar objects.

Now I have to split the lists into multiple lists based on a property of these objects.

Here is the sample data set
List:
A{1, A}
A{2, A}
A{3, B}
A{4, B}
A{5, B}
A{6, C}

Result should be

List 1:
A{1, A}
A{2, A}

List2:
A{3, B}
A{4, B}
A{5, B}

List3:
A{6, C}

Any body has a easier way doing this...
Costi Ciudatu
Ranch Hand

Joined: Oct 24, 2006
Posts: 74
Perhaps commons-collections could help you with such a task.

But I would try to put those all in a map, using that splitting/filtering property as key and a List as value:


After this block, map.values() will return a Collection of List objects containing what you are looking for.
In case the splitter property is of a custom type, make sure that type has a proper equals() and hashCode() implementations.
forums UseR
Ranch Hand

Joined: Feb 24, 2009
Posts: 169
I can only use Java 1.4

Not sure if your code will work in my case.



Costi Ciudatu
Ranch Hand

Joined: Oct 24, 2006
Posts: 74
For Java 4, just strip down the generics from my code.
I actually have to split the ArrayList into an array.

You need to split the ArrayList into an array of lists ? If so, map.values().toArray().
forums UseR
Ranch Hand

Joined: Feb 24, 2009
Posts: 169
Costi Ciudatu wrote:Perhaps commons-collections could help you with such a task.

But I would try to put those all in a map, using that splitting/filtering property as key and a List as value:


Can you please explain whats going on here..., I have not worked much with Maps.., and I have only used Java 1.4
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

(Although I'd refactor out that middle chunk of the iteration.)
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

(Or, if feeling particularly refactory:)(Dealing with people unfamiliar with refactoring for a job, so aways coming up with examples to show them :)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Any easy way to split an Arraylist into multiple lists based on a property of the objects?