Collection中的函数式接口

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值