Piszu
Piszu

Reputation: 443

What structure should I use to store key and list of possible values?

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?

Upvotes: 2

Views: 174

Answers (2)

fps
fps

Reputation: 34460

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

Upvotes: 2

Ryuzaki L
Ryuzaki L

Reputation: 40078

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);

Upvotes: 1

Related Questions