gpt4 book ai didi

java - 从java中的arrayList中删除一个项目

转载 作者:行者123 更新时间:2023-12-01 07:34:19 24 4
gpt4 key购买 nike

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

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

最佳答案

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

strLine = br.readLine().trim()

然后将您的 while 循环实现为:

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

关于java - 从java中的arrayList中删除一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14090313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com