I’m trying to read a line of text from a text file and put each line into a Map so that I can delete duplicate words (e.g. test test) and print out the lines without the duplicate words. I must be doing something wrong though because I basically get just one line as my key, vs each line being read one at a time. Any thoughts? Thanks.
public DeleteDup(File f) throws IOException {
line = new HashMap<String, Integer>();
try {
BufferedReader in = new BufferedReader(new FileReader(f));
Integer lineCount = 0;
for (String s = null; (s = in.readLine()) != null;) {
line.put(s, lineCount);
lineCount++;
System.out.println("s: " + s);
}
}
catch(IOException e) {
e.printStackTrace();
}
this.deleteDuplicates(line);
}
private Map<String, Integer> line;
To be honest, your question isn’t particularly clear – it’s not obvious why you’ve got the
lineCount, or whatdeleteDuplicateswill do, or why you’ve named thelinevariable that way when it’s not actually a line – it’s a map from lines to the last line number on which that line appeared.Unless you need the line numbers, I’d use a
Set<String>instead.However, all that aside, if you look at the
keySetoflineafterwards, it will be all the lines. That’s assuming that the text file is genuinely in the default encoding for your system (which is whatFileReaderuses, unfortunately – I generally useInputStreamReaderand specify the encoding explicitly).If you could give us a short but complete program, the text file you’re using as input, the expected output and the actual output, that would be helpful.