2

I want to store information about filetype and possible files extension. What I want to do is if I provide file extension and this extension is on the list I will return key for it.

Eg:

Map<Filetype, List<String>> extensionMapping= new HashMap<>();
extensionMapping.put(Filetype.IMAGE, Arrays.asList("jpg", "jpeg"));
extensionMapping.put(Filetype.WORD, Arrays.asList("doc", "docx"));
extensionMapping.put(Filetype.EXCEL, Arrays.asList("xls", "xlsx", "xlsm"));
extensionMapping.put(Filetype.PPT, Arrays.asList("ppt", "pptx", "pptm"));`

And then I want to do something like this:

return extensionMapping.get().contains("jpg");

which for string "jpg" returns me Filetype.IMAGE.

Which collection should I use?

Piszu
  • 443
  • 1
  • 8
  • 24

2 Answers2

2

I would create a reverse map, with the keys being the extension and the values the file type:

Map<String, Filetype> byExtension = new HashMap<>();
extensionMapping.forEach((type, extensions) -> 
        extensions.forEach(ext -> byExtension.put(ext, type)));

Now, for a given extension, you simply do:

FileType result = byExtension.get("jpg"); // FileType.IMAGE
fps
  • 33,623
  • 8
  • 55
  • 110
  • 1
    This is probably the better answer. Here is another posting to a similar question, where the mapping is being made part of the enum through a `static Map`: https://stackoverflow.com/a/12659023/744133 – YoYo Apr 23 '19 at 13:25
1

I mean you can do that now also by having same structure Map<Filetype, List<String>>. In Map any of values (which is List of strings contains "jpg") will return Filetype.IMAGE or else it will return Filetype.None

extensionMapping.entrySet().stream().filter(entry->entry.getValue().contains("jpg")).map(Map.Entry::getKey)
      .findFirst().orElse(Filetype.None);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98