16
Oct

stack / vector removeIf example

Java 8 introduces a new method available for Collection types: removeif().

It accepts a predicate which defines the condition on which the elements should be removed. It returns a boolean where a true response means that at least one item has been removed and false otherwise:

e.g

Collection<String> st = new Stack<>();
st.add(“Hello”);
st.add(“my”);
st.add(“dear”);
st.add(“world”);

st.removeIf(s -> s.contains(“my”));

The above example will remove “my” from stack.

Another way to achieve same:

for (Iterator<String> it = st.iterator(); it.hasNext();) {
if ((it.next().equalsIgnoreCase(“My”))) {
it.remove();
}
}
System.out.println(st);  // will remove my from stack