tags:

views:

38

answers:

2

I have a list of Customers. Each customer has an address and some customers may actually have the same address. My ultimate goal is to group customers based on their address. I figure I could either put the customers in some sort of list-based structure and sort on the addresses, or I could drop the objects into some sort of map that allows multiple values per key.

I will now make a pretty picture:

List:
A1 - C1, A1 - C2, A2 - C3, A3 - C4, A3 - C5

Map:
A1 A2 A3
C1 C3 C4
C2    C5

Which option (or any others) do you see as the best solution? Are there any existing classes that will make development easier?

+4  A: 

You can use Map<K, Collection<V>> for this where K is the Address and V is the Customer. Another option is the Google Collections Multimap<K, V> which is a more convenienced wrapper for Map<K, Collection<V>>.

BalusC
+1  A: 

You could accomplish this using Lambdaj's group method. Something like this:

Group<Customer> custByAddr = group(customers, by(on(Customer.class).getAddress().getId())

You could then get the list of customers by group by calling custByAddr.find("addressId1")

Read more at http://code.google.com/p/lambdaj/wiki/LambdajFeatures in the Grouping Items section.

I haven't tested this, but it should give you a starting place. I've used LambdaJ many times, and it's extremely useful.

Joey Gibson