I’ve a Tuple class which has:
private class Tuple {
private int fileno;
private int position;
public Tuple(int fileno, int position) {
this.fileno = fileno;
this.position = position;
}
}
I also have an hashmap which refrences this list like
Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>();
Now there is a scenario where i need to count how many words in a file: The data is as follows:
abc 10.txt
abc 10.txt
abc 10.txt
abc 12.txt
abc 12.txt
ghost 15.txt
and so on....
Now how to count number of occurences of the above? It is easy but i’ve been coding so long and also new to java.
I also learnt duplicates can’t go into hashmap! Thanks.
To add data to list:
List<Tuple> idx = index.get(word);
if (idx == null) {
idx = new LinkedList<Tuple>();
index.put(word, idx);
}
idx.add(new Tuple(fileno, pos));
Above code just dumps the data, Now i will compare with words from a string array[].
All i need at end is like this:
abc 10.txt count – 3
abc 12.txt count – 2
ghost 15.txt count – 1
I’m not sure if map helps/i need to use a list again/write a function to do this? Thanks!
I solved the above problem with simple condition statements! Thanks @codeguru
/*
consider all cases and update wc as along
Lesson learnt - Map does not handle duplicates
- List does not work
- spend half a day figuring out
*/
if(wordInstance == null && fileNameInstance == null) {
wordInstance = wordOccurence;
fileNameInstance = files.get(t.fileno);
}
if(wordInstance == wordOccurence && fileNameInstance ==files.get(t.fileno)) {
wc++;
}
if(wordInstance == wordOccurence && fileNameInstance !=files.get(t.fileno)) {
wc=0;
fileNameInstance = files.get(t.fileno);
wc++;
}
if(wordInstance != wordOccurence && fileNameInstance ==files.get(t.fileno)) {
wc=0;
wordInstance = wordOccurence;
wc++;
}
I think you may be making this more complicated than it needs to be. I suggest that you take a step back from the computer. First you should take a simple input example and work out, by hand, what the output should be. Next, write a few sentences (in your native language) describing the steps you took to work out this output. From there, you need to refine your description until you can easily translate it into Java.