[英]Removing an item from an arrayList in java
我有一个程序从文件中获取输入,将文件中的每个单词保存为标记,然后将每个标记添加到数组列表中。
问题是例如出现了arrayList [[cat],“ dog”,“”,“,”,“ bird”],而我不希望arrayList中有空格。
并如下所示设置读取的文件:
cat dog
bird
显然是空行引起了空格,但是空行是必需的。
无论如何,我的代码如下:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class NewMain{
public static void main(String[] args){
try{
FileInputStream fstream = new FileInputStream("Filename");
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
List<String> listOfWords = new ArrayList<String>();
while((strLine = br.readLine()) != null){
String [] tokens = strLine.split("\\s+");
String [] words = tokens;
for(String word : words){
listOfWords.add(word);
System.out.print(word);
System.out.print(" ");
}
System.out.print("\n");
}
System.out.println(listOfWords);
List<String> space = new ArrayList<String>();
String[] spaces = {" "};
space.addAll(Arrays.asList(spaces));
editList(listOfWords,space);
System.out.println(listOfWords);
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public static void editList(Collection<String> list1, Collection<String> list2){
Iterator<String> it = list1.iterator();
while(it.hasNext()){
if(list2.contains(it.next())) {
it.remove();
}
}
}
}
String[] spaces = {" "};
应该删除空格,因为我已经通过从非文件arrayList删除空格进行了测试。 而且奇怪的是,如果我将其更改为String[] spaces = {"cat"};
它将cat从arrayList中删除。
原因很明显。 可能的解决方案是使用此方法:
strLine = br.readLine().trim()
然后将while
循环实现为:
while (strLine != null && !strLine.isEmpty()) { //do stuff }
在您的for循环中添加一个if条件:
for(String word : words){
if(!word.equals("")) /* OR if( (word.length > 0) )*/ {
listOfWords.add(word);
System.out.print(word);
System.out.print(" ");
}
}
尝试删除空字符串-由于您是通过空格模式\\s+
分割的,因此列表中不会包含" "
,但会包含""
:
String[] spaces = {""};
但是不要在以后删除它们, 不要首先添加它们 !
if (word.length() == 0) continue;
listOfWords.add(word);
(并添加您需要的任何类似过滤器!)
这不仅简单 。 效率也更高。 从数组列表中删除元素的成本为O(n)
。 因此,用于过滤的代码的复杂度为O(n^2)
(通过复制到第二个列表中,您可以将其降低到O(n)
)。 首先,不添加元素基本上是免费的。 您的解析甚至会以这种方式变得更快-仍在O(n)
,但比第二步中的过滤更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.