开发者

How to create list filter

开发者 https://www.devze.com 2023-01-07 11:03 出处:网络
In my List, I want to ignore certain entries(create list filter), by ignore I mean remove. If my list contains 开发者_运维问答A to Z String elements, let say I want to remove B, F and Z.

In my List, I want to ignore certain entries(create list filter), by ignore I mean remove. If my list contains 开发者_运维问答A to Z String elements, let say I want to remove B, F and Z.

How would I do this with var args, arbitrary number of elements to be removed from the list?

Thank you


You can make use of List#removeAll().

List<String> alphabet = new ArrayList<String>();
alphabet.add("A");
alphabet.add("B");
alphabet.add("C");
alphabet.add("D");
alphabet.add("E");
alphabet.add("F");
alphabet.add("G");
// Etc..
List<String> toRemove = Arrays.asList("B", "F"); // Takes varargs!

alphabet.removeAll(toRemove);

System.out.println(alphabet); // A, C, D, E, G


Using guava

final Iterable<String> filtered = Iterables.removeIf(asList("A","B","C", "Z"), new Predicate<String>(){
    public boolean apply(final String element){
       // your filter, eg
       return element.equals("A");
    )
}


Quick guess (using varargs):

void removeFromList(List<Object> list, Object ... filterElements){
  for(Object elm:filterElements){
    while(list.remove(elm));
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号