lambda表达式

/**
 * Predicate
 *     method : test(T t)
 * 判断,返回boolean
 */
public static void testPredicate(){
    Predicate predicate = x -> x.compareTo(BigDecimal.ZERO) > 0;
    Predicate 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
 *     method : accept(T t)
 * 消费一条消息,无返回值
 */
public static void testConsumer(){
    Consumer> consumer = x -> {
        for (Student student : x) {
            student.setScore(student.getScore() * 100);
        }
    };
    List 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 function = x -> x.getScore();
    Student s = new Student(89d);
    System.out.println(s);
    System.out.println(function.apply(s));
}

/**
 * 生产一条消息
 */
public static void testSupplier(){
    Supplier supplier = () -> "supplier return";
    System.out.println(supplier.get());
}

你可能感兴趣的:(lambda表达式)