gpt4 book ai didi

Java Stream 接口(interface)映射函数参数类型

转载 作者:行者123 更新时间:2023-12-01 19:52:24 25 4
gpt4 key购买 nike

Stream接口(interface)中的map函数定义如下:

<R> Stream<R> map(Function<? super T,? extends R> mapper)

函数参数列表与函数接口(interface)自己的规范一致

Interface Function<T,R>

方法是

R apply(T t)

意味着它需要一个 T 但返回一个 R。但我正在运行这段代码

import java.util.stream.*;
import java.util.function.*;

public class T3 {
public static void main(String...args){
mapTest();
}
static void mapTest(){
Stream<String> s = Stream.of("monkey", "gorilla", "bonobo");
s.map(String::length).forEach(System.out::print); // 676
}
}

并且想知道,它是如何工作的,但参数类型似乎不匹配?没有简单的方法来解释它,但我的理解是函数应该接受 T 类型的输入并返回 R 类型。当它在流中使用时,它接受 String 类型的输入并返回 int 类型。 (即 string.length())。但是 Stream.map 被输入为返回与流相同的类型(即 R,在本例中为 String,即不是 int):<R> Stream<R> map(Function<? super T,? extends R> mapper) 。那么这是怎么回事呢?提前致谢。

最佳答案

map -您在 Stream 上调用的方法需要 mapper类型为Function<? super T, ? extends R> 。所以这里有两个泛型类型:TRT是已处理流的元素类型。 R根据 API

The element type of the new stream

您的mapper需要 String并返回其 String.length()String.length()的返回类型是 int 。这是结果流的元素类型。所以你的映射器已输入

Function<? super String, ? extends Integer>

作为int自动装箱为 Integer

关于Java Stream 接口(interface)映射函数参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50931973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com