-3

There are several strings in my array list and some of them start with a specific prefix -for example ("AFI"). I want to remove these strings from the array list. Other strings contain more than two words, for example ("Edit this template"). I want to delete them too, as well as the strings that contain only one word.

I know that I should use patterns, but can't find exactly what I should use. Would be happy if you help me to deal with this problem.

Soutzikevich
  • 991
  • 3
  • 13
  • 29
Rumato
  • 147
  • 7
  • Your question doesn’t help in understanding the question fully. Need more info like, how does the element look? out of which you want to delete the afore mentioned strings? – Unknown Dec 06 '19 at 17:06
  • the elements in your arraylist are all String ? – kevin ternet Dec 06 '19 at 17:15
  • I've downloaded all html code from a page, accroding to a pattern found the information that I need and put it into Array List of Strings. I have some elements that are not useful for me. These elements have some features that can be helpful to find them and delete (I've described these features in my question). So I think that patterns can be helpful in this case but can't find appropriate to perform a task. – Rumato Dec 06 '19 at 17:18
  • You should give a minimal example of what you have and what the desired result should look like in order to get a qualified answer. Sometimes a few lines of code are better than a bunch of explantion text. – Eritrean Dec 06 '19 at 18:28
  • Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). Your question does not conform with the community's guidelines, and will soon be closed by a moderator. You should edit it appropriately if you expect to get any answers. Good questions usually include: **A desired outcome or result**, **What you have tried so far to solve your problem** and more. – Soutzikevich Dec 06 '19 at 21:09

1 Answers1

0

You can use List#removeIf with a predicate which complies with your rules. Assuming you have something like this:

List<String> myList = new ArrayList<>();
myList.add("AFIxyz boo");
myList.add("Foo Bar");
myList.add("Bar Baz");
myList.add("AFI afi");
myList.add("Edit this template");
myList.add("Watch");

System.out.println("Before removing:");
System.out.println(myList);

//remove all which start with "AFI"
myList.removeIf(s -> s.startsWith("AFI"));

//remove all which have more than two words
myList.removeIf(s -> s.split(" ").length > 2);

System.out.println("\nAfter removing:");
System.out.println(myList);
Eritrean
  • 15,851
  • 3
  • 22
  • 28
  • I think this is more correct `myList.removeIf(s -> (s.startsWith("AFI") || s.split(" ").length != 2));` Strings with length == 1 need to be removed as well. (I assume the strings will always have a length of 1 or more). – Soutzikevich Dec 06 '19 at 21:19