Java笔记-函数式编程

Consumer

Consumer表示消费一个字符串。
基本写法:

public class ConsumerTest {

    public static Consumer<String> printString = new Consumer<String>() {
        @Override
        public void accept(String s) {
            System.out.println(s);
        }
    };

    public static void main(String[] args) {
        List<String> list = List.of("111", "222", "333");
        list.stream().forEach(printString);
    }
}

lambda写法

public static Consumer<String> printString = s -> System.out.println(s);

方法引用写法(其实就是简化的lambda表达式)

public static Consumer<String> printString = System.out::println;

Supplier

public class SupplierTest {

    public static Supplier<String> studentIdGenerator = () -> "student id:"+ new Random().nextInt(10);

    public static void main(String[] args) {
        System.out.println(studentIdGenerator.get());
    }
}

Function

Function第一个参数是输入值,第二个是输出值,就是T转换为R的函数。

import java.util.Objects;

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Function<T, R> {
...
}
public class FunctionTest {

    public static Function<Integer, String> integerToString = i -> Integer.toString(i);

    public static void main(String[] args) {
        List<Integer> list = List.of(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3));
        System.out.println(list.stream().map(integerToString).collect(Collectors.joining(",")));
    }
}
输出:1,2,3

Predicate

public class PreDecideTest {

    public static Predicate<String> isBlank = s -> s.isBlank();

    public static void main(String[] args) {
        List<String> list = List.of("", "1", "2");
        System.out.println(list.stream().filter(isBlank).count());
    }
}
输出:1
public class PreDecideTest {

    public static Predicate<String> isBlank = s -> s.isBlank();
    public static Predicate<String> startWithA = s -> s.startsWith("A");

    public static void main(String[] args) {
        List<String> list = List.of("", "A11", "B22", "");
        System.out.println(list.stream().filter(isBlank.or(startWithA)).count());
    }
}
输出:3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值