HashMap from List of Files

2019-09-22 07:56发布

I'd like to explore the option of using a HashMap to keep track of changes between files. I'm using a few config/text files to give a set of documents of status:

The config file looks like:

STATUS1 = "Doc1.pdf, Doc2.xls, Doc5.doc"
STATUS2 = "Doc8.pdf, Doc6.doc"
STATUS3 = "Doc10.pdf"
...

Instead of having to create a separate HashMap for each instance like so:

Map<String, String> map1 = new HashMap<String, String>();
Map<String, String> map2 = new HashMap<String, String>();
Map<String, String> map3 = new HashMap<String, String>();

map1.put("STATUS1", "Doc1.pdf");
map2.put("STATUS1", "Doc2.xls");
map3.put("STATUS1", "Doc5.doc");

I'd like to have only a single Map with the key of the status and the values mapped to that key.

I don't need help in parsing the file, I just need assistance in implementing the HashMap or Map so I can add this functionality. If there are other datatypes or methods of organizing this data, I'd like to hear your opinions on that.

Any help would be much appreciated.

标签: java hashmap
1条回答
仙女界的扛把子
2楼-- · 2019-09-22 08:18

You can use a MultiMap, which stores multiple values for the same key.

  1. Multimap
   Multimap<String, String> myMultimap = ArrayListMultimap.create();
   // Adding some key/value

  myMultimap.put("STATUS1", "somePDF");
  myMultimap.put("STATUS1", "someDOC");
  myMultimap.put("STATUS1", "someXCL");   
  myMultimap.put("STATUS2","someFormat");

  // Getting the size
  int size = myMultimap.size();
  System.out.println(size);  // 4

  // Getting values
  Collection<string> stats1 = myMultimap.get("STATUS1");
  System.out.println(stats1); // [somePDF, someDOC, someXCL]

2 . HashMap

With HashMap you can have something like,

    List<String> listOfDocs = new ArrayList<String>();
    listOfDocs.add("somePDF");
    listOfDocs.add("someDOC");
    listOfDocs.add("someFormat");

    HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); 
    // key would be your STATUS
    // Values would be ListOfDocs you need.

   map.put("STATUS1", listOfDocs);
   map.put("STATUS2", listOfDocs2);
   map.put("STATUS3", listOfDocs3);

Hope this helps. Let me know if you have questions.

查看更多
登录 后发表回答