views:

78

answers:

4

Hi,

I have a list of objects which I want to perform an operation on. However I firstly need to divide the list into separate lists such that all items with the same parentID are in the same list, and then the operation is performed on each list separately (the reason being that the operation takes the parentID of the objects as a parameter).

What is the best way to separate a list based on a given property of it's elements, as required here? The highest number of objects that will be passed in the original list is < 10,000 and normally will be < 1,000.

All help is much appreciated!

+1  A: 

I would recommend writing an Iterator that wraps an Iterator, returning only elements that match what you want. You could then write an implementation of Iterable that takes an Iterable, returning such an iterator (this would allow you to use an enhanced for loop).

Jonathan
Downside is you end up iterating over the same elements at least `m` times, where `m` is the number of unique parent ids.
Mark Peters
@Mark True, but you don't waste space if you only wanted to process the elements, not actually separate into separate lists. I'm not exactly sure which the questioner wants.
Jonathan
+6  A: 

It sounds like you might want to use Multimaps.index from Guava. That will build you a multi-map, where each key has a collection of elements.

The keyFunction passed into index would be a Function which just retrieves the property from a single element.

Jon Skeet
Always one step ahead! +1.
Mark Peters
Seems like a good alternative, to use the Multimap. If you are concerned about dependency the code from hvgotcodes will be also a valid and simple alternative.
cuh
+2  A: 

Create a

 Map <IdType, List<YourObject>> map

loop thru the list, and for each id do something like

List theList = map.get(id);
if (theList == null ) {
   // create a new list, add it to the map under the id

}  

// add the item to theList

then you can loop thru the map's entries and you have a list of objects for each id. This approach does not require you to know how many different ids are in your list to begin with....

hvgotcodes
This is a good alternative to not having Guava.
Mark Peters
This is not quite the typical idiom... you can just create and add the list if you get null, and then afterwards add the item. Then you only have to add the item in one place rather than two.
ColinD
@colinD, absolutely correct; fixed...
hvgotcodes
A: 

If you're okay with adding a 3rd party library, Google's Guava supplies various utilities which could help you out.

Specifically, use Collections2.transform like this:

Collection myOriginalList;
Collection mySplitList1 = Collections2.transform(myOriginalList, new Function() { /* method to filter out parent ID 1 */ });
... // repeat for each parent id you're interested in
Tom Tresansky