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?

4
  • 3
    It seems like your extensions are unique per key, so I'd opt for a Map<String, FileType> where the key is the extension. Commented Feb 12, 2019 at 20:19
  • 1
    Why not Map <String, Filetype> is that's you most common query? Commented Feb 12, 2019 at 20:20
  • 1
    I feel current one is also good `Map<Filetype, List<String>> Commented Feb 12, 2019 at 20:29
  • EnumMap is a better container for cases where the key is of a single Enum type. Commented Apr 23, 2019 at 13:31

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/a/12659023/744133
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.