java 8 中為Iterable接口新增了forEach(Consumer action)默認方法,該函數式接口的唯一抽象函數為accept(T t),可以用它來遍歷Collection集合元素。
public class CollectionTest{ public static void main(String[] args){ Collection books = new HashSet(); books.add("java"); books.add("python"); books.add("js"); books.forEach(obj -> System.out.Iterator的forEachRemaining(Consumer action)函數的參數也是Consumer接口,注意,Iterable接口是Collection的父接口,而Iterator不是,它的對象的創建必須依賴一個Collection對象。Collection books = new HashSet();Iterator it = books.iterator();Iterator對象的遍歷
public class CollectionTest{ public static void main(String[] args){ Collection books = new HashSet(); books.add("java"); books.add("python"); books.add("js"); Iterator it = books.iterator(); it.forEachRemaining(obj -> System.out.println(obj)); }}Predicate接口的抽象函數是boolean test(obj)。java 8為Collection集合新增了removeIf(Predicate filter)方法,將Collection對象中的元素依次傳入該接口對象的test方法中,若返回值是true,則刪除該元素,完成批量刪除操作。
Collection books = new HashSet();books.add("java");books.add("javascrMySQL");//刪除了"java"和"mysql"元素books.removeIf(obj -> ((String)obj).length()<6);與Iterator接口類似,Comparator接口還有一個與它很相似的接口Comparable,不過Comparator接口是函數式接口,Comparable不是。TreeSet類是通過調用集合中元素的compareTo(Object obj)方法來比較元素之間的大小關系來進行排序,compareTo方法是Comparable接口中的方法,所以TreeSet集合中的元素必須是同一類的對象,而且該類必須實現Comparable接口。TreeSet集合中元素必須是同一類的對象的原因是:調用compareTo方法時,都會將比較對象強制轉換為相同類型對象,否則兩者無法比較。
再來說Comparator接口,該接口只有一個int compare(T o1,T o2)方法:如果該方法返回正整數,則表示o1大于o2,返回0表示相等,返回負數表示o1小于o2。通過compare函數可以實現TreeSet的定制排序,方法是在創建TreeSet對象時提供一個Comparator對象與之關聯。
class M{ int age; public M(int age){ this.age = age; } public String toString(){ return "M[age"+age+"]";}}public class TreeSetTest{ public static void main(String[] args){ //此處Lambda表達式的目標類型是Comparator TreeSet ts = new TreeSet((o1,o2) -> { M m1 = (M)o1; M m2 = (M)o2; if (m1.age>m2.age){ return -1;} else if(m1.age<m2.age){ return 1;} else{ return 0;} }); ts.add(new M(5)); ts.add(new M(3)); ts.add(new M(4)); System.out.println(ts); }}新聞熱點
疑難解答