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

如何通过IntFunction使Collections.toArray返回元素翻倍的数组?

问题原因与解决方案

为什么你的代码不生效?

Collection.toArray(IntFunction<T[]>)中的IntFunction参数仅用于创建指定长度的空数组,它接收的参数是集合的元素个数,而非集合中的单个元素。你之前的代码里,把参数val当成了集合元素,但实际上val是集合的大小(这里是3),所以你创建的是[3*2=6]的数组,随后toArray方法会把原集合的元素填充到这个数组里(数组长度不够时会自动扩容并填充原元素),最终得到的还是原集合的元素数组。

正确实现方式

方法一:使用Stream API(推荐)

通过Stream的map方法先将每个元素翻倍,再转换为数组:

Set<Integer> itemSet = new HashSet<>();
itemSet.add(1);
itemSet.add(3);
itemSet.add(5);

Integer[] itemArr = itemSet.stream()
                           .map(num -> num * 2)
                           .toArray(Integer[]::new);
// 输出结果(顺序可能因HashSet无序性略有不同):[2, 6, 10]

方法二:手动遍历填充

如果不使用Stream,可以先创建对应长度的数组,再遍历集合填充翻倍后的值:

Set<Integer> itemSet = new HashSet<>();
itemSet.add(1);
itemSet.add(3);
itemSet.add(5);

Integer[] itemArr = new Integer[itemSet.size()];
int idx = 0;
for (Integer num : itemSet) {
    itemArr[idx++] = num * 2;
}

内容的提问来源于stack exchange,提问作者ash_kmt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:45:32