I need to create a Map with string as a key and list of integers as a value. I have created the Map, I created tokenization of words which I get from txt file. Right now I am trying to put keys and values into map, but I am still receving errors. I am wondering that maybe my Map has been created wrong, but I don't see any other way to create this map.
I've been trying to add this map with "put" function, in this way I cannot even compile this program
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
//Map<String, Integer> map = new HashMap<String, Integer>();
int numberOfFiles;
File directory = new File("C:/Users/User/Desktop/documents java project/");
numberOfFiles = directory.list().length;
for(int i = 1; i <= numberOfFiles; i++) {
//tokenization of string
String filePath = "C:/Users/User/Desktop/documents java project/document "+ i +".txt";
String fileData = readFile(filePath);
String delimiter = " ";
String fileWords [] = fileData.split(delimiter);
//words.add(fileWords);
int numberOfWords = fileWords.length;
for(int j = 0; j < numberOfWords; j++) {
map.put(fileWords[j], i);
}
}
}
Your Map
is expecting the value to be a List<Integer>
but you are trying to put an int
into it instead:
map.put(fileWords[j], i);
Instead, you need to create a List<Integer>
and put that as the value, like:
if (!map.containsKey(fileWords[j])) {
map.put(fileWords[j], new ArrayList<>());
}
map.get(fileWords[j]).add(i);
This will add a new empty List
to your Map
if it doesn't already exist, and then it will add the value of i
to the list. If it does already exist, it will just add i
to the list that is already there.
This can also be done with Map.computeIfAbsent()
if the above is too wordy for your tastes:
map.computeIfAbsent(fileWords[j], k -> new ArrayList<>()).add(i);
If you don't want to store duplicates, you can use a Set
instead. Change your declaration to:
Map<String, Set<Integer>> map = new HashMap<>();
And later, to add items:
map.computeIfAbsent(fileWords[j], k -> new HashSet<>()).add(i);