【发布时间】:2014-07-21 14:06:10
【问题描述】:
我有一个项目列表,比如List<Item> listOfItems,每个项目都有一个键,比如String cluster_key。我想将具有相同cluster_key 的所有项目聚集到一个桶中,给我结果List<Bucket> listOfBuckets。存储桶列表一开始是空的。
关于如何优雅地使用 Java 的任何建议?也许有散列?
我能想到 2 个不太优雅的实现:
- 蛮力,我们遍历
listOfItems,并为每个项目遍历桶列表,直到找到匹配项。如果我们找到匹配项,则将该项目添加到存储桶中。否则,
.
for item in listOfItems {
for bucket in listOfBuckets {
if item.getKey() equals bucket.getKey()
add item to bucket
else
create new bucket
add item to bucket
add bucket to listOfBuckets
}
}
- 排序,然后聚类:
.
sort listOfItems by their cluster_key;
get first item from listOfItems;
create a bucket, currentBucket, with key: firstItem.getKey()
add first item to bucket
for item in listOfItems, starting at the second item {
if item.getKey() equals currentBucket.getKey()
add item to currentBucket
else
create new bucket
add item to new bucket
add new bucket to listOfBuckets
set new bucket to currentBucket
}
【问题讨论】: