1

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

0

1 Answer 1

1

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"); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer but i do not want this much complicated the things that you use for your code i even do not learn it yet so if you solve my problem using loops so i can understand it. I never use this type of things in my code but i learn a new thing . Thank you
Read the link that i added in my answer @Faheem
Yeh i already see that but i do not submit this as my assignment because this topic is not included in our course so i do not use this in my program sorry but thank you so much for your answer i really appreciate this. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.