一點一點看JDK源碼(五)java.util.ArrayList 後篇之removeIf與Predicatehtml
liuyuhang原創,未經容許禁止轉載java
本文舉例使用的是JDK8的APIide
Predicate爲jdk1.8新增接口,由ArrayList.removeIf(Predicatep)調用。post
使用起來也比較方便,從ArrayList中移除Predicate 中test方法的返回值(boolean)來肯定是否刪除,url
示例代碼以下:spa
1 package com.FM.ArrayListStudy; 2 3 import java.util.ArrayList; 4 import java.util.function.Predicate; 5 6 public class RemoveIfInArrayListStudy { 7 public static void main(String[] args) { 8 ArrayList<Integer> list = new ArrayList<Integer>(); 9 for (int i = 0; i < 20; i++) { 10 list.add(i + 1); 11 } 12 System.out.println(list); 13 list.removeIf(new Predicate<Integer>() { 14 15 @Override 16 public boolean test(Integer t) { 17 if (t % 2 == 1) { 18 return true; 19 } else { 20 return false; 21 } 22 } 23 }); 24 System.out.println(list); 25 } 26 }
運行結果以下:code
比較簡單,很少廢話htm
以上!blog