How can you filter out something from a Java ArrayList like if you have:
And the filter is "How" it will remove Joe and Mike.
This question is related to
java
collections
arraylist
I agree with a previous answer that Google Guava is probably helping a lot here, readability-wise:
final Iterables.removeIf(list, new Predicate<String>() {
@Override
public boolean apply(String input) {
if(input.contains("How")) { //or more complex pattern matching
return true;
}
return false;
}
});
Please note that this is basically a duplicate of Guava - How to remove from a list, based on a predicate, keeping track of what was removed?
As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":
var list = new List<string>();
list.AddRange(new string[] {
"How are you?",
"How you doing?",
"Joe",
"Mike", });
foreach (string str in list.Where(s => s.Contains("How")))
{
Console.WriteLine(str);
}
Console.ReadLine();
Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:
// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[]
{"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
if (!it.next().contains("How"))
it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
}
System.out.println("List After: " + list);
OUTPUT:
List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]
write your self a filter function
public List<T> filter(Predicate<T> criteria, List<T> list) {
return list.stream().filter(criteria).collect(Collectors.<T>toList());
}
And then use
list = new Test().filter(x -> x > 2, list);
This is the most neat version in Java, but needs JDK 1.8 to support lambda calculus
Source: Stackoverflow.com