英文:
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("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);
}
答案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 = "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()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论