我正在努力实现,我正在寻找根据日期对列表进行分组的方法。我丢失了如下属性:
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/