如何在Java中迭代LinkedList并从中删除某些单词
正在尝试从LinkedList中删除一些单词。这是我用于测试的数据:如何在Java中迭代LinkedList并从中删除某些单词,java,collections,linked-list,Java,Collections,Linked List,正在尝试从LinkedList中删除一些单词。这是我用于测试的数据: String[]stopwords={“the”,“and”} nwl=LinkedList(Arrays.asList(input)) String input=“和的” 我希望得到的结果是:[of],但我得到的是:[The,end,of] for (Iterator<String> iter = nwl.iterator(); iter.hasNext();) { String word = iter.ne
String[]stopwords={“the”,“and”}代码>
nwl=LinkedList(Arrays.asList(input))代码>
String input=“和的”
我希望得到的结果是:[of]
,但我得到的是:[The,end,of]
for (Iterator<String> iter = nwl.iterator(); iter.hasNext();) {
String word = iter.next();
for (int i = 0; i < nwl.size(); i++){
if(word == stopwords[i]) {
iter.remove();
}
}
}
for(迭代器iter=nwl.Iterator();iter.hasNext();){
String word=iter.next();
对于(int i=0;i
比较字符串时,需要使用.equals()
方法,而不是=
运算符。因此,您需要将if(word==stopwords[i])
更改为if(word.equals(stopwords[i])
较长版本:
粗略地说,=
操作符确定两个变量是否指向同一个对象(在我们的例子中,word
和stopwords[i]
是否指向同一个字符串对象)。.equals()
方法确定两个对象是否相同(按内容)。如果您的情况下,程序无法产生所需的输出,因为您有两个不同的字符串持有相同的内容。因此,通过==
比较它们会产生false
,而通过.equals()
比较它们会产生'true'
编辑
阅读了链接中发布的程序后,我发现了两件事:首先,内部for循环的条件必须更改为I
。其次,newWordList
对象没有正确初始化。它是新的LinkedList(Arrays.asList(parts))
,这意味着LinkedList
将包含一个字符串元素,其值为的and,这不是您想要的。您希望LinkedList
包含四个字符串元素,如下所示:
- 元素0:
the
- 要素1:
和
- 要素2:
要素3:该
因此,需要将初始化更改为newlinkedlist(
Arrays.asList(parts.split(“”))
。具体来说,parts.split(“”
将给定字符串(split
)分解为单独的单词,返回这些单词的数组
public static void main (String[] args) throws java.lang.Exception
{
String[] stopwords = { "the", "and" };
String parts = "the and of the";
LinkedList<String> newWordList = new LinkedList<String>(
Arrays.asList(parts.split(" ")));
for (Iterator<String> iter = newWordList.iterator(); iter.hasNext();) {
String word = iter.next();
for (int i = 0; i < stopwords.length; i++) {
if (word.equals(stopwords[i])) {
iter.remove();
}
}
}
System.out.println(newWordList.toString());
}
publicstaticvoidmain(字符串[]args)抛出java.lang.Exception
{
String[]stopwords={“the”,“and”};
字符串parts=“的和”;
LinkedList newWordList=新建LinkedList(
Arrays.asList(parts.split(“”));
for(Iterator iter=newWordList.Iterator();iter.hasNext();){
String word=iter.next();
for(int i=0;i
如果要删除重复项,请使用设置
如果要迭代
并删除,请使用迭代器
,但首先要确定operation@FlyingZombie谢谢你的评论。我想保留重复项,这就是为什么我不使用Set
。虽然最初这个问题似乎是关于字符串比较的,但在更仔细的检查中,它也是关于字符串拆分/集合初始化的。感谢您的回答,我做了您建议的更改,但我仍然得到相同的输出。也许在for
循环中还有其他错误?以下链接包含测试程序。已完成答复。请看一看谢谢你详细的回答和解释。按照预期工作,这也帮助我理解了一些事情。