Java 8 removing an item from array/array list based on regex

  • A+

Is there a better way to achieve the following in java 8?

String regex = "^SACHI"; for (String temp : personalNames ) {     if (temp.matches(regex)){          personalNames.remove(temp);     } } 


You can use


You could also use the simpler

personalNames.removeIf(s -> s.matches("^SACHI")); 

but it will perform Pattern.compile("^SACHI") under the hood, for every element in the worst case. Note that the Pattern created by compile is immutable and can be shared, hence, you could also create it only once, like

static final Pattern REMOVAL_PATTERN = Pattern.compile("^SACHI"); 

and use it like


asPredicate() uses find() instead of matches(), but since your pattern has the ^ anchor, it makes no difference. The method asMatchPredicate() for getting a predicate using matches() has been added in JDK 11.

If all you want, is to match a literal string at the beginning, you can also use

personalNames.removeIf(s -> s.startsWith("SACHI")); 

which does not have the regex initialization overhead.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: