---
# System prepended metadata

title: removeIf的用法
tags: [ocpjp]

---

# removeIf的用法
```java=
public static void main(String[] args) {
    String[] arr = {"Hi","How","Are","You"};
    List<String> arrList = new ArrayList<>(Arrays.asList(arr));
    if(arrList.removeIf((String s) ->{return s.length()<=2;})) {
        System.out.println(s+"removed");
    }
}
```
### What is the result?
A. Hi removed
**B. Compilation fails.**
C. An UnsupportedOperationException is thrown at runtime.
D. The program compiles, but it prints nothing.
- [x] **Answer:B**
:::info
程式第5行，會顯示請宣告s的區域變數，因為removeIf那邊宣告的s，在第5行是看不見的。所以Compilation fails
:::

:::success
### removeIf : 删除Collection中符合條件的元素，傳回boolean值

範例:
```java=
class Person{
     private String name;
     private Integer age;
     private String gender;
     
     Person(String name,Integer age,String gender){
    	 this.name = name;
    	 this.age = age;
    	 this.gender = gender;
     }
     //省略getter , setter , toString
```
```java=
List<Person> list = new ArrayList<>();
    list.add(new Person("John", 22, "男"));
    list.add(new Person("Camiol", 19, "女"));
    list.add(new Person("Andy", 34, "男"));
    list.add(new Person("Joyce", 30, "男"));
    list.add(new Person("Judy", 25, "女"));

    list.removeIf(p -> p.getAge()>25);
    System.out.println(list);
```
**Console:** 只留下25歲以內的人
```
[
    Person [name=John, age=22, gender=男], 
    Person [name=Camiol, age=19, gender=女], 
    Person [name=Judy, age=25, gender=女]
]
```
:::

###### tags: `ocpjp`

