简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM