Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

java - HashMap from List of Files

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...