Question

I'm trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words on a line separated by commas. I read each file with the following code (not complete):

ArrayList<String> temp = new ArrayList<>();

FileInputStream fis;
fis = new FileInputStream(fileName);

Scanner scan = new Scanner(fis);

while (scan.hasNextLine()) {
    Scanner input = new Scanner(scan.nextLine());
    input.useDelimiter(",");
    while (scan.hasNext()) {
        String md5 = scan.next();
        temp.add(md5);
    }
}
scan.close();    

return temp;

Each file contains almost 1 million words (I don't know the exact number), so I'm not entirely sure that the above code works correctly - but it seems to.

I now want to find out how many words are exclusive to the first file/arraylist. To do so I planned on using list1.removeAll(list2) and then checking the size of list1 - but for some reason this is not working. The code:

public static ArrayList differentWords(String fileName1, String fileName2) {
    ArrayList<String> file1 = readFile(fileName1);
    ArrayList<String> file2 = readFile(fileName2);

    file1.removeAll(file2);

    return file1;
}

My main method contains a few different calls and everything works fine until I reach the above code, which just causes the program to hang (in netbeans it's just "running").
Any idea why this is happening?

Was it helpful?

Solution

You are not using input in

while (scan.hasNextLine()) {
  Scanner input = new Scanner(scan.nextLine());
  input.useDelimiter(",");
  while (scan.hasNext()) {
    String md5 = scan.next();
    temp.add(md5);
  }
}

I think you meant to do this:

while (scan.hasNextLine()) {
  Scanner input = new Scanner(scan.nextLine());
  input.useDelimiter(",");
  while (input.hasNext()) {
    String md5 = input.next();
    temp.add(md5);
  }
}

but that said you should look into String#split() that will probably save you some time:

while (scan.hasNextLine()) {
  String line = scan.nextLine();
  String[] tokens = line.split(",");
  for (String token: tokens) {
    temp.add(token);
  }
}

OTHER TIPS

try this :

for(String s1 : file1){
    for(String s2 : file2){
        if(s1.equals(s2)){file1.remove(s1))}
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top