美文网首页
lambda表达式

lambda表达式

作者: 白驹过隙_忽然而已 | 来源:发表于2020-11-23 17:51 被阅读0次
    /**
     * Predicate<T>
     *     method : test(T t)
     * 判断,返回boolean
     */
    public static void testPredicate(){
        Predicate<BigDecimal> predicate = x -> x.compareTo(BigDecimal.ZERO) > 0;
        Predicate<BigDecimal> predicate2 = x -> x.compareTo(BigDecimal.TEN) <= 0;
        System.out.println(predicate.test(new BigDecimal(-1)));
        System.out.println(predicate.and(predicate2).test(new BigDecimal(10)));
    }
    
    /**
     * Consumer<T>
     *     method : accept(T t)
     * 消费一条消息,无返回值
     */
    public static void testConsumer(){
        Consumer<List<Student>> consumer = x -> {
            for (Student student : x) {
                student.setScore(student.getScore() * 100);
            }
        };
        List<Student> list = new ArrayList<>(2);
        list.add(new Student(0.3));
        list.add(new Student(0.5));
        for (Student student : list) {
            System.out.println(student.getScore());
        }
        consumer.accept(list);
        for (Student student : list) {
            System.out.println(student.getScore());
        }
    }
    
    /**
     * Function
     *      method : R apply(T t)
     * 讲 T 转换成 R
     */
    public static void testFunction(){
        Function<Student,Double> function = x -> x.getScore();
        Student s = new Student(89d);
        System.out.println(s);
        System.out.println(function.apply(s));
    }
    
    /**
     * 生产一条消息
     */
    public static void testSupplier(){
        Supplier<String> supplier = () -> "supplier return";
        System.out.println(supplier.get());
    }

    相关文章

      网友评论

          本文标题:lambda表达式

          本文链接:https://www.haomeiwen.com/subject/tyuviktx.html