You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stream.toList()替换collect(Collectors.toList())后JWKSet构造方法报错的问题咨询

Stream.toList()替换collect(Collectors.toList())后JWKSet构造方法报错的问题咨询

大家好,我最近碰到一个Java Stream的奇怪问题,想跟大家请教一下。

在我们的代码中,我们使用nimbus-jose-jwt库的JWKSet类,写了一个方法来创建后续逻辑用到的映射。具体逻辑是把RSAKey列表通过Stream处理后,生成JWKSet实例。

原本我用collect(Collectors.toList())来收集Stream的结果,代码是正常工作的,但按照SonarQube的建议换成toList()后,编译器直接报错了,错误信息如下:

Cannot resolve constructor 'JWKSet(List)

编译器还提示我要把参数强制转换成JWK类型,但我确认过RSAKey是继承自抽象类JWK的,理论上应该是兼容的啊。我实在搞不懂为什么这两个收集列表的方法会有不一样的表现。

下面是我的测试代码和实际代码:

final List<RSAKey> keys = Collections.singletonList(identityToRSAKey(certificate));
    
// 验证两个方法生成的列表类型一致
List<RSAKey> list = keys.stream().map(RSAKey::toPublicJWK).toList();
List<RSAKey> collect = keys.stream().map(RSAKey::toPublicJWK).collect(Collectors.toList());

// 这段代码可以正常运行
JWKSet mySet = new JWKSet(keys
        .stream()
        .map(RSAKey::toPublicJWK)
        .collect(Collectors.toList()));

// 这段代码编译报错
JWKSet mySet2 = new JWKSet(keys
        .stream()
        .map(RSAKey::toPublicJWK)
        .toList() );

// 我们实际使用的代码
return new JWKSet(keys
    .stream()
    .map(RSAKey::toPublicJWK)
    .collect(Collectors.toList() ))
    .toPublicJWKSet()
.toJSONObject();

另外,我们调用的JWKSet构造方法是这个:

public JWKSet(List<JWK> keys) {
    this(keys, Collections.emptyMap());
}

有没有大佬能帮我解释一下这是为什么呀?

备注:内容来源于stack exchange,提问作者Mattias Gradin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:03:07