将单个元素添加到NavigableMap中的List

时间:2012-03-29 15:14:05

标签: java

我希望能够根据文件输入地图的日期对文件进行排序。键是日期,值是在相应日期添加的n个文件列表。但是,我需要能够一次将文件添加到List中 - 但我仍然坚持使用语法。如何从Map.put()中调用List.add()?这是我的代码:

public static NavigableMap<String, List<File>> myFiles = new TreeMap<>();
String today = new Date().toString();
File currentFile;
myFiles.put(today, currentFile);  //problem here adding currentFile

2 个答案:

答案 0 :(得分:1)

这是因为类型为safetyp(使用泛型)。 today指向文件列表,您只想将一个文件添加到该列表中。

我建议您首先检查地图中是否有today,如果没有添加支持列表,请将currentFile添加到该列表中:

if (!myFiles.containsKey(today))
    myFiles.put(today, new ArrayList<File>());

myFiles.get(today).add(currentFile);

答案 1 :(得分:1)

您应该有两个级别,因此首先检查当天是否已有列表,否则您创建一个空级别并将其添加到集合中。

void addFile(File file)
{
  String today = new Date().toString();
  List<File> listForDay = myFiles.get(today);

  // if there are no files for today then create and empty list for the day
  if (listForDay == null)
  {
    listForDay = new ArrayList<File>();
    myFiles.put(today, listForDay);
  }

  listForDay.add(file);
}