Reputation: 11
i am trying to compare array list of string with array of string by using .equal but its not working i am trying to remove element from array list if it is equal to arrays element every time it is executing if part and not removing element from array list
public ArrayList removeCommonWords(ArrayList<String> fileTokens){
System.err.println("size of arraylist: \t"+fileTokens.size()+"\t size of array: \t"+stoppingWordsGlobal.length);
for(int i=0;i<fileTokens.size();i++){
for (int j=0;j<stoppingWordsGlobal.length;j++) {
if (fileTokens.get(i).equals(stoppingWordsGlobal[j])) {
fileTokens.remove(i);
System.out.print("\nremoving token number :"+"\t"+i+"\t"+fileTokens.get(i)+"\t"+stoppingWordsGlobal[j]);
}
}
}
return fileTokens;
}
Upvotes: 0
Views: 688
Reputation: 4551
Convert the String[] stringArray
to an ArrayList<String>
:
ArrayList<String> strings = new ArrayList<>(Arrays.asList(stringArray));
Then simply remove shared content from the original list:
originalList.removeAll(strings);
Or in one line (untested):
originalList.removeAll(new ArrayList<String>(Arrays.asList(stringArray));
Upvotes: 1
Reputation: 367
Try this:
main method code:
ArrayList<String> list= new ArrayList<String>();
list.add("angularjs");
list.add("javascript");
list.add("java");
list.add("c");
Test test= new Test();
System.out.println(test.removeCommonWords(list));
your method:
String[] stoppingWordsGlobal={"nodejs","java","angularjs"};
public ArrayList removeCommonWords(ArrayList<String> fileTokens){
System.err.println("size of arraylist: \t"+fileTokens.size()+"\t size of array: \t"+stoppingWordsGlobal.length);
for(int i=0;i<fileTokens.size();i++){
for (int j=0;j<stoppingWordsGlobal.length;j++) {
if (fileTokens.get(i).equals(stoppingWordsGlobal[j])) {
String removedString=fileTokens.get(i);
fileTokens.remove(i);
System.out.print("\nremoving token number :"+"\t"+i+"\t"+removedString+"\t"+stoppingWordsGlobal[j]);
}
}
}
return fileTokens;
}
output is:
size of arraylist: 4 size of array: 3
removing token number : 0 angularjs angularjs
removing token number : 1 java java
Upvotes: 0