JAVA中Function的使用
时间: 2024-05-04 20:15:19 浏览: 13
Java中的Function是一个函数式接口,它接受一个参数并返回一个结果。它的定义如下:
```
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
```
其中,T表示函数的输入参数类型,R表示函数的返回值类型。apply()方法接收一个T类型的参数,并返回一个R类型的结果。
Function可以用来对输入值进行操作和转换,例如将一个字符串转换为整数,或者将一个对象列表映射为另一个属性列表。下面是一些使用Function的示例:
1. 将字符串转换为整数
```
Function<String, Integer> stringToInteger = Integer::valueOf;
Integer result = stringToInteger.apply("123"); // result = 123
```
2. 将对象列表映射为另一个属性列表
```
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
Function<Person, String> getName = Person::getName;
List<String> names = people.stream().map(getName).collect(Collectors.toList()); // names = ["Alice", "Bob", "Charlie"]
```
在这个例子中,我们定义了一个Function,用来获取Person对象的名称。然后,我们使用Stream API将people列表中的每个Person对象映射为其名称,并将结果收集到一个字符串列表中。
3. 组合多个Function
```
Function<String, Integer> stringToInteger = Integer::valueOf;
Function<Integer, Integer> square = x -> x * x;
Function<String, Integer> stringToSquaredInteger = stringToInteger.andThen(square);
Integer result = stringToSquaredInteger.apply("2"); // result = 4
```
在这个例子中,我们定义了两个Function,一个用来将字符串转换为整数,另一个用来计算整数的平方。然后,我们使用andThen()方法将它们组合成一个新的Function,该Function将字符串转换为整数,并计算其平方。最后,我们使用这个新的Function将字符串"2"转换为4。