简体   繁体   English

从Java中的arrayList中删除项目

[英]Removing an item from an arrayList in java

I have a program that takes input from a file, saves each word in the file as a token and then adds each token to an array list. 我有一个程序从文件中获取输入,将文件中的每个单词保存为标记,然后将每个标记添加到数组列表中。

The problem is that the arrayList comes up as for example ["cat","dog"," "," ","bird"], and I don't want the spaces in the arrayList. 问题是例如出现了arrayList [[cat],“ dog”,“”,“,”,“ bird”],而我不希望arrayList中有空格。

And the file that is read is set up as shown below: 并如下所示设置读取的文件:

cat dog


bird

It is obvious that it is the blank lines cause the spaces, but the blank lines are necessary. 显然是空行引起了空格,但是空行是必需的。

Anyway, my code is below: 无论如何,我的代码如下:

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();
            }  
       }
}
} 

The String[] spaces = {" "}; String[] spaces = {" "}; should remove the blank spaces, as I have tested it by removing spaces from an non-file arrayList. 应该删除空格,因为我已经通过从非文件arrayList删除空格进行了测试。 And the strange thing is that if I change it to String[] spaces = {"cat"}; 而且奇怪的是,如果我将其更改为String[] spaces = {"cat"}; it will remove cat from the arrayList. 它将cat从arrayList中删除。

The reason is quite obvious. 原因很明显。 A possible solution is to use this: 可能的解决方案是使用此方法:

strLine = br.readLine().trim()

then implement your while loop as: 然后将while循环实现为:

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

in your for loop add an if condition: 在您的for循环中添加一个if条件:

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

Try removing empty strings - since you split via the whitespace pattern \\s+ , you will not have " " in your list, but "" : 尝试删除字符串-由于您是通过空格模式\\s+分割的,因此列表中不会包含" " ,但会包含""

String[] spaces = {""};

But instead of removing them afterwards, don't add them in the first place ! 但是不要在以后删除它们, 不要首先添加它们

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

(and add any similar filters you need!) (并添加您需要的任何类似过滤器!)

This is not just simpler . 不仅简单 It is also much more efficient. 效率也更高。 Removing an element from an array list costs O(n) . 从数组列表中删除元素的成本为O(n) So the complexity of the code you used for filtering is O(n^2) (you could get this down to O(n) by copying into a second list). 因此,用于过滤的代码的复杂度为O(n^2) (通过复制到第二个列表中,您可以将其降低到O(n) )。 Not adding the elements in the first place is essentially for free; 首先,不添加元素基本上是免费的。 your parsing will even become a bit faster this way - still in O(n) , but faster than filter in a second step. 您的解析甚至会以这种方式变得更快-仍在O(n) ,但比第二步中的过滤更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM