【问题标题】:Removing an item from an arrayList in java从java中的arrayList中删除一个项目
【发布时间】:2012-12-30 11:27:43
【问题描述】:

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

问题是 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。

【问题讨论】:

标签: java netbeans collections arraylist


【解决方案1】:

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

strLine = br.readLine().trim()

然后将while 循环实现为:

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

【讨论】:

  • 我认为这只是针对 空行 的特殊情况的一种解决方法。假设他会在; 上拆分,并且有一个像word;word;;;word 这样的行,他仍然会得到两个empty words。这绝对不是错误的。有时您想过滤空行,但保留空词。
  • 是的,这取决于程序的目标。在这种情况下,按照说明实现while循环后,他可以很容易地检查每个令牌是否也为空,然后进行相应的处理。
【解决方案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(" ");   
           }   
        } 

【讨论】:

  • 完美运行。不敢相信我没有尝试过。谢谢
  • word.length() == 0 比比较空字符串更合理。看我的回答。
  • @Anony-Mousse:不管怎样......!我已经更新了ans。让 OP 知道他需要在哪里添加条件的要点。然后由他决定,哪种形式的条件适合他。不过感谢您的建议:)
【解决方案3】:

尝试删除 empty 字符串 - 因为您通过空格模式 \s+ 进行拆分,所以您的列表中将没有 " ",但 "":

String[] spaces = {""};

但是不要在之后删除它们,不要一开始就添加它们

if (word.length() == 0) continue;
listOfWords.add(word);

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

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

【讨论】:

  • 也可以,谢谢。这只是我的程序的一小部分,我正在处理不是我创建的大文件,因此手动删除每个文件的所有空格的工作量太大。不过谢谢
  • “一开始就不要添加它们”,我指的是您将listOfWords.add(word);它们添加到列表中的代码;不是原始数据!
  • 我还解释了为什么在解析时过滤比对列表进行后处理更快。如果您的文件这么大,您应该会注意到差异。
猜你喜欢
  • 2011-03-31
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多