目前我使用的是Java 6.出于......的原因。现在我想按照日期对列表中的所有元素进行分组,因此我不会为每个日期分配多个条目。
让我们说我有一个结构上看起来像这样的列表:
+==============+=============+
| 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
的两个独立实例。第一个(完整)按Date
使用Collections.Sort()
排序。然后第二个(空)循环遍历整个列表,对于我们找到的每个日期,它将在该日期之前递增newPottyUses
。找到新日期后,它会将所有数据插入新列表,并重置newPottyUses
,然后继续循环直至完成。
对于一些物品,这很好。对于包含许多不同类型的大型列表,它已经达到了无法维护的程度。我无法帮助,但感觉在这里有一些轮子重新发明。
有更好的方法吗? Java 6和8解决方案都将受到赞赏,但目前只能检查6个。
答案 0 :(得分:2)
使用地图:
typedef struct __attribute__((packed))
{
uint8_t frameLength;
unsigned frameType :3;
uint8_t payloadBytes;
uint8_t payload[RADIO_RX_PAYLOAD_WORST];
} RADIO_PACKET;
答案 1 :(得分:2)
您是否考虑过使用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}