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

huangapple go评论74阅读模式
英文:

How can I replace a value in a List using an iterator ( Java )

问题

这是您的代码翻译:

所以基本上我正在编写一个简单的程序用户输入一个字符串然后将该字符串转换为一个列表其中倒数第二个元素的每个出现都会被替换为最后一个元素

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

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

public static void main(String args[])
{

Scanner input = new Scanner(System.in);

System.out.println("输入列表");
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);
}

希望这对您有所帮助。

英文:

So basically I'm writing a simple program where the user inputs a string and then that string is turned into a List where every occurrence of the second to last element is replaced with the last one.

So if the program inputs
a b c a b c
the program outputs
a c c a c

This is what I got so far but I can't run the program for some reason I was wondering what I'm doing wrong.

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

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

List&lt;String&gt; list = new ArrayList&lt;String&gt;(Arrays.asList(s.split(&quot; &quot;)));


String replacewith;
String replace;

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

Iterator&lt;String&gt; 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);
}

答案1

得分: 0

你可以使用Java 8的流(streams)来解决你的问题。

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()));
英文:

You can use java8 streams to solve your problem.

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

huangapple
  • 本文由 发表于 2020年10月7日 03:08:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64232317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定