Reputation: 42
Question : How to remove all Strings in rayList that end with the same Last Letter as lastLetter?
I write my code like this so i remove all string from ArrayList that has same end character as lastLetter
import java.util.*;
public class LastLetter
{
public static ArrayList<String> go(ArrayList<String> rayList, char lastLetter)
{
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i<rayList.size(); i++)
{
char last = rayList.set(i, rayList.get(raylist.size() - 1));
if(lastLetter == last)
result.add(rayList.remove(i));
}
return result;
}
}
I do not know if it is working or not and i do not understand how to make runner for this code please correct any problems from my code and make a runner so we can run this code properly.
My try to make runner:
import java.util.*;
class Runner
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("fred");
list.add("at");
list.add("apple");
list.add("axe");
list.add("bird");
list.add("dog");
list.add("kitten");
list.add("alligator");
list.add("chicken");
LastLetter h = new LastLetter();
System.out.println(h.go(list),"m");
}
}
Please make a proper runner for this code.
Thank you
Upvotes: 1
Views: 275
Reputation: 40088
You should not remove elements while iterating the ArrayList
, for more information read this post the simplest solution will be using removeif
rayList.removeIf(val-val.endsWith(String.valueOf(lastLetter)));
I would also suggest to take string as argument instead of char
public static ArrayList<String> go(ArrayList<String> rayList, String lastLetter) {
rayList.removeIf(val-val.endsWith(lastLetter));
return result;
}
And since go
is static method in LastLetter
class you can call it by using class name
LastLetter.go(Arrays.asList("My name is faheem"), "m");
Upvotes: 1