String Arraylist get the item starting with this string

后端 未结 5 1709
长情又很酷
长情又很酷 2021-02-09 15:35

I have a array list in which I bind the data This is a example

MyStrings =new ArrayList();
MyStrings.add(\"Dog\");
MyStrings.add(\"Cat\");
MyString         


        
5条回答
  •  难免孤独
    2021-02-09 16:07

    You can use the apache commons-collections library as well:

    CollectionUtils.filter(myStrings,
      new Predicate() {
        public boolean evaluate(Object o) {
           return !  ((String)o).startsWith("c");
        }
      }
    };
    

    Any object for which the "evaluate" method of the Predicate class returns false is removed from the collection. Keep in mind, that like the solution above using the Iterator, this is destructive to the list it is given. If that is an issue, you can always copy the list first:

    List filtered = new ArrayList(myStrings);
    CollectionUtils.filter(filtered, ...);
    

提交回复
热议问题