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

Faheem
  • 42
  • 9

1 Answers1

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"); 
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • 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 – Faheem Mar 01 '20 at 23:10
  • Read the link that i added in my answer @Faheem – Ryuzaki L Mar 01 '20 at 23:24
  • 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! – Faheem Mar 01 '20 at 23:26