繁体   English   中英

Java:按类型对列表元素进行分组

[英]Java: Group list elements by type

目前,我正在使用Java6。出于某些原因。 现在,我想按日期对列表中的所有元素进行分组,因此每个日期没有多个条目。

假设我有一个结构看起来像这样的列表:

+==============+=============+
| dateHappened |  pottyUses  |
+==============+=============+
| 10/09/2015   |     255     |
+--------------+-------------+
| 10/09/2015   |     256     |
+--------------+-------------+
| 10/09/2015   |     254     |
+--------------+-------------+

我想把它变成这样:

+==============+=============+
| dateHappened |  pottyUses  |
+==============+=============+
| 10/09/2015   |     765     |
+--------------+-------------+

列表代码如下所示:

public class PottyCollection implements Comparable<PottyCollection>
{
    public PottyCollection(final Date dateHappened, final int pottyUses)
    {
        this.dateHappened = dateHappened;
        this.pottyUses = pottyUses;
    }
    final public Date dateHappened;
    final public int pottyUses;
}

到目前为止,我已经创建了两个单独的PottyCollection实例。 使用Collections.Sort()将第一个(完整)按Date排序。 第二个(空)然后遍历整个列表,对于我们找到的每个日期,它将在该日期之前增加newPottyUses 找到新日期后,它将所有这些数据插入到新列表中,并重置newPottyUses ,然后继续循环直到完成。

对于几个项目,这很好。 对于具有许多不同类型的大型列表,它已经到了很难维护的地步。 我禁不住觉得这里正在重新发明轮子。

有没有更好的办法? Java 6和8解决方案都将受到赞赏,但目前只能检查6个。

使用地图:

Map<Date, PottyCollection> map = new HashMap<>();
for (PottyCollection pc : originalList) {
    PottyCollection existing = map.get(pc.dateHappened);
    if (existing == null) {
        map.put(pc.dateHappened, pc);
    }
    else {
        map.put(pc.dateHappened, new PottyCollection(pc.dateHappened, pc.pottyUses + existing.pottyUses));
    }
}
Collection<PottyCollection> reduced = map.values();

您是否考虑过使用TreeMap<K,V>代替List<E>

TreeMap的元素自然根据其键进行排序。 此外,通过重写put方法,可以检测是否已经存在某个日期。

代码示例:

import java.util.Date;
import java.util.TreeMap;

public class PottyCollection extends TreeMap<Date, Integer> {
    @Override
    public Integer put(Date key, Integer value) {
        if (containsKey(key)) {
            return super.put(key, get(key) + value);
        } else
            return super.put(key, value);
    }


    public static void main(String[] args) {
        PottyCollection collection = new PottyCollection();
        collection.put(new Date(0), 100);
        collection.put(new Date(1), 55);
        collection.put(new Date(0), 55);

        System.out.println(collection);
    }
}

输出:

{Thu Jan 01 01:00:00 CET 1970=155, Thu Jan 01 01:00:00 CET 1970=55}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM