从java中的arrayList中删除项

时间:2012-12-30 11:27:44

标签: java netbeans collections arraylist

我有一个程序从文件中获取输入,将文件中的每个单词保存为一个标记,然后将每个标记添加到一个数组列表中。

问题是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"};,它将从arrayList中删除cat。

3 个答案:

答案 0 :(得分:3)

原因很明显。一种可能的解决方案是使用它:

strLine = br.readLine().trim()

然后将while循环实现为:

while (strLine != null && !strLine.isEmpty()) { //do stuff }

答案 1 :(得分:2)

在for循环中

添加if条件:

for(String word : words){
            if(!word.equals(""))  /* OR if( (word.length > 0) )*/  {
            listOfWords.add(word);
            System.out.print(word);
            System.out.print(" ");   
           }   
        } 

答案 2 :(得分:2)

尝试删除字符串 - 因为您通过空格模式\s+进行拆分,所以会在列表中包含" ",但{ {1}}:

""

但不是之后删除它们,不要在第一时间添加它们

String[] spaces = {""};

(并添加您需要的任何类似过滤器!)

不仅仅是简单。它也更有效率。从数组列表中删除元素的费用为if (word.length() == 0) continue; listOfWords.add(word); 。因此,用于过滤的代码的复杂性为O(n)(您可以通过复制到第二个列表将其降低到O(n^2))。首先不添加元素基本上是免费的;你的解析甚至会以这种方式变得更快 - 仍然在O(n),但比第二步中的过滤更快。