java - 迭代列表并根据日期分组

标签 java

我正在努力实现,我正在寻找根据日期对列表进行分组的方法。我丢失了如下属性:

List<Attribute> attributes

哪里 Attribute.java如下

public class Attribute
{
    Integer getValue();
    List<String> getString();
    Date getDate();
}

我正在寻找一种方法,在迭代 Attribute 列表时,我可以创建一个元素列表(当前日期)和基于具有相同 IntegerValue 的日期(过去)的元素映射。

我的代码如下:

List<Attribute> currentElement = new ArrayList<Attribute>();
Map<Integer, List<Attribute>> historicalElement = new HashMap<Integer, List<Attribute>>();

//iterating the entire list
for(final Attribute attribute : attributes) 
{
  if(attribute.getDate() == currentDate)
  {
      currentElement.add(attribute);
  }
  if(attribute.getDate() < currentDate)
  {
      historicalElement.put(attribute.getValue(), attribute)     
  }
}

声明

historicalElement.put(attribute.getValue(), attribute)     

不会工作,因为

The method put(Integer, List<Attribute>) in the type Map<Integer,List<Attribute>> is not applicable for the arguments (Integer,   Attribute).

有什么方法可以实现该映射,而不是键入强制转换到 List。

谢谢!!!

最佳答案

转换到列表根本没有帮助。您只会得到一个ClassCastException。最简单的方法可能是这样的:

if(attribute.getDate() < currentDate)
{
    List<Attribute> list = historicalElement.get(attribute.getValue());
    if(list == null){
        list = new ArrayList<>();
        historicalElement.put(attribute.getValue() , list);
    }

    list.add(attribute);  
}

关于java - 迭代列表并根据日期分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630929/

相关文章:

java - 无法正确对齐输出

java - 如何在 JavaFX 中设置字体的字母间距(又名跟踪)?

java - 模块中的包可见性

java - 为什么Java没有宏?

java - 如何使用贝塞尔曲线近似椭圆以填充给定的矩形?

java - Spring 和数据问题

java - 从 arraylist 返回具有最高值的对象?

java - 单击后退时 Android 应用程序未正确关闭

java - 如何在文本文件中附加多个文本

java - 我正在尝试使用 gui 制作一个三角形面积计算器,但是当我编译它时,我不断收到这个奇怪的错误