如何使用迭代器(Java)替换列表中的值

如何使用迭代器(Java)替换列表中的值,java,list,arraylist,iterator,Java,List,Arraylist,Iterator,基本上,我在写一个简单的程序,用户输入一个字符串,然后这个字符串被转换成一个列表,在这个列表中,倒数第二个元素的每一次出现都被最后一个元素替换 所以如果程序输入 a b c a b c 程序输出 a c a c 这就是我到目前为止所得到的,但由于某些原因,我无法运行该程序。我想知道我做错了什么 public static void main(String args[]) { Scanner input = new Scanner (System.in); System.out.pr

基本上,我在写一个简单的程序,用户输入一个字符串,然后这个字符串被转换成一个列表,在这个列表中,倒数第二个元素的每一次出现都被最后一个元素替换

所以如果程序输入 a b c a b c 程序输出 a c a c

这就是我到目前为止所得到的,但由于某些原因,我无法运行该程序。我想知道我做错了什么

public static void  main(String args[])
{
    
Scanner input = new Scanner (System.in);

System.out.println("Enter in list");
String s = input.nextLine();

List<String> list = new ArrayList<String>(Arrays.asList(s.split(" ")));


String replacewith;
String replace;

replacewith = list.get(list.size()-1);
replace = list.get(list.size()-2);

Iterator<String> iterator = list.iterator();
int i = 0;

while(iterator.hasNext()) {
   String value = iterator.next();
   
   if(value.equals(replace))
   {  
       iterator.remove();
       list.add(i,replacewith);
       
   }
   i++;
}

System.out.println(list);
}
publicstaticvoidmain(字符串参数[])
{
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入列表”);
字符串s=input.nextLine();
List List=newarraylist(Arrays.asList(s.split(“”));
字符串替换为;
字符串替换;
replacewith=list.get(list.size()-1);
replace=list.get(list.size()-2);
迭代器迭代器=list.Iterator();
int i=0;
while(iterator.hasNext()){
字符串值=迭代器.next();
如果(值等于(替换))
{  
iterator.remove();
列表。添加(i,替换为);
}
i++;
}
系统输出打印项次(列表);
}

您可以使用java8流来解决您的问题

    String replaceWith = "c";
    String replace = "b";
    System.out.println(Arrays.asList("a", "b", "c", "a", "b", "c").stream()
            .map(c -> c.equals(replace) ? replaceWith : c)
            .collect(Collectors.toList()));

迭代器期望仅通过该迭代器对列表进行修改(直到它完成迭代)。因此不能使用
list.add(i,replacewith)当迭代还没有完成时。@Pshemo啊,我明白了,你知道我将预期值添加到该索引的另一种方法吗?老实说,我不确定我是否正确理解了你的任务。既然任务是“倒数第二个元素的每次出现都被最后一个元素替换”,那么
a b c a b c
(6个字符,第二个是
b
)是如何变成
a c a c
(为什么5个字符?为什么
a
没有被替换?)无论如何,如果您想在迭代过程中替换某些元素,可以使用
ListIterator
而不是
Iterator
,并调用其
set(newValue)
方法。@Pshemo谢谢!我完全忘记了列表迭代器,是的,你误解了我的意图,但不用担心,因为你给出了正确的解决方案。谢谢你,我从来没有尝试过使用java8,因为我对java还很陌生,但这很有效!