开发者

Group Objects by Common Key

I have a lis开发者_JAVA百科t 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?


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>>.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜