Collection中的函数式接口

来源:互联网 发布:sql怎删查改 编辑:程序博客网 时间:2024/04/29 17:44

Collection中的函数式接口

1. Consumer

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.println("迭代元素:"+obj));    }}

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));    }}

2. Predicate

Predicate接口的抽象函数是boolean test(obj)。java 8为Collection集合新增了removeIf(Predicate filter)方法,将Collection对象中的元素依次传入该接口对象的test方法中,若返回值是true,则删除该元素,完成批量删除操作。

Collection books = new HashSet();books.add("java");books.add("javascript");books.add("mysql");//删除了"java"和"mysql"元素books.removeIf(obj -> ((String)obj).length()<6);

3. Comparator

与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);    }}
0 0