【问题标题】:How to map a list of items into another list of buckets, given a key for each item?给定每个项目的键,如何将项目列表映射到另一个桶列表?
【发布时间】: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
}

【问题讨论】:

    标签: java hash bucket


    【解决方案1】:

    按相同键对项目进行分组的最快方法是遍历您的列表并将每个项目添加到正确的存储桶(在需要时创建存储桶),这与您的第一个示例类似。

    但是,如果您为您的 bucketList 使用 HashMap,您可以在恒定时间内将项目添加到您的桶中,这将为您提供 O(n) 而不是 O(n^2) 复杂度的算法。

    未经测试,但你明白了

    HashMap<String,ArrayList<Item>> bucketList = new HashMap();
    
    for (Item i : listOfItems) {
        if(!bucketList.containsKey(i.getKey()) {
            bucketList.put(i.getKey(),new ArrayList());
        }
    
        buckList.get(i.getKey()).add(item);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2021-12-22
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多