Reputation: 159
So I have a list of folder names that I want to separate by the keyword '-' and store then in a map. In that list of folder there might be multiple names before the '-' character so I want to get all the values that contains the same key and store that for that value. Also the name after '-' character might be different later on. For example, this is some of the folder names I have:
20190220103811-2019_Release_1
20190304201669-master
20190314142918-2019_Release_1
20190314143655-develop
20190315134912-2019_Release_1
20190315135106-develop
20190315143607-develop
For all develop, I want to store the values for the develop key, and same for the rest. This is what I have so far:
File[] filteredDirectoryList = file.listFiles(textFilter);
String[] splitArr = new String[filteredDirectoryList.length];
ArrayList<String> listOfBuiltDate = new ArrayList<>();
// looping through, splitting by '-' and adding it to a map
for(File temp : filteredDirectoryList) {
System.out.println(temp.getName());
splitArr = temp.getName().split("-");
if(temp.getName().contains(splitArr[1])) {
listOfBuiltDate.add(splitArr[0]);
}
listOfDirectories.put(splitArr[1], listOfBuiltDate);
}
My current output is:
Key=2019_Release_1, Value=[20190220103811, 20190304201669, 20190314142918, 20190314143655, 20190315134912, 20190315135106, 20190315143607]
Key=develop, Value=[20190220103811, 20190304201669, 20190314142918, 20190314143655, 20190315134912, 20190315135106, 20190315143607]
Key=master, Value=[20190220103811, 20190304201669, 20190314142918, 20190314143655, 20190315134912, 20190315135106, 20190315143607]
But I want it to be:
Key=2019_Release_1, Value=[20190220103811, 20190314142918, 20190315134912]
Key=develop, Value=[20190314143655, 20190315135106, 20190315143607]
Key=master, Value=[20190304201669]
I'm not sure how can I add the values to a list and add them to the map. I was thinking adding multiple lists that will only add based on each key (2019_Release_1) but there might be more keys so it might not be good.
Upvotes: 1
Views: 69
Reputation: 9331
Your approach is correct but you can't use the same List for all entries.
You must have a List for each Key
So your HashMap needs to change to:
HashMap<String, List<String>> listOfDirectories = new HashMap<>();
And then populate it like so:
for(File temp : filteredDirectoryList) {
splitArr = temp.getName().split("-");
//HERE IS WHERE YOU CREATE THE NEW LIST IF THE KEY DOESN'T HAVE IT
if(!listOfDirectories.containsKey(splitArr[1])) {
listOfDirectories.put(splitArr[1], new ArrayList<>());
}
listOfDirectories.get(splitArr[1]).add(splitArr[0]);
}
Upvotes: 1