Java 8 BiFunction示例

本文深入探讨了Java 8中的BiFunction接口,介绍了如何使用它接受两个参数并返回一个对象。示例涵盖了基本用法、与Function结合使用的方法、工厂模式的应用,以及如何根据条件过滤。此外,还提供了相关的Java 8教程和示例链接。
摘要由CSDN通过智能技术生成

在Java 8中, BiFunction是功能接口; 它接受两个参数并返回一个对象。

BiFunction.java
@FunctionalInterface
public interface BiFunction<T, U, R> {

      R apply(T t, U u);

}
  • T –函数的第一个参数的类型。
  • U –函数第二个参数的类型。
  • R –函数结果的类型。

1. BiFunction <T,U,R>

1.1本示例使用两个Integers并返回IntegerDoubleList

Java8BiFunction1.java
package com.mkyong;

import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;

public class Java8BiFunction1 {

    public static void main(String[] args) {

        // takes two Integers and return an Integer
        BiFunction<Integer, Integer, Integer> func = (x1, x2) -> x1 + x2;

        Integer result = func.apply(2, 3);

        System.out.println(result); // 5

        // take two Integers and return an Double
        BiFunction<Integer, Integer, Double> func2 = (x1, x2) -> Math.pow(x1, x2);

        Double result2 = func2.apply(2, 4);

        System.out.println(result2);    // 16.0

        // take two Integers and return a List<Integer>
        BiFunction<Integer, Integer, List<Integer>> func3 = (x1, x2) -> Arrays.asList(x1 + x2);

        List<Integer> result3 = func3.apply(2, 3);

        System.out.println(result3);

    }

}

输出量

5
16.0
[5]

2. BiFunction <T,U,R> + Function <T,R>

2.1此BiFunction接受两个Integer并返回Double ,然后使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值