【问题标题】:I need to input IntFunction such that Collections.toArray(IntFunction<T> generator) returns an array containing n times of values in the collection我需要输入 IntFunction 以便 Collections.toArray(IntFunction<T> generator) 返回一个包含集合中 n 倍值的数组
【发布时间】:2022-11-15 21:34:33
【问题描述】:

我有一组整数:

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

我想将它转换成一个整数数组,其值是原始 Set 中值的 2 倍。

我试过了:

Integer [] itemArr1 = itemSet.toArray((val)->{
            Integer [] it = new Integer [] {val*2};
            return it;
            }
        );

但价值并没有翻倍。

【问题讨论】:

标签: java-8


【解决方案1】:

像这样尝试。

Set<Integer> itemSet = new HashSet<Integer>();
itemSet.add(1);
itemSet.add(3);
itemSet.add(5);
  • 流式传输集合并将每个元素映射到当前值的两倍。
  • 然后作为 Integer[] 数组返回。
Function<Set<Integer>, Integer[]> duplicate = 
        (a)->a.stream().map(i->i*2).toArray(Integer[]::new);
        
Integer[] result = duplicate.apply(itemSet);

System.out.println(Arrays.toString(result));

印刷

[2, 6, 10]

您也可以按如下方式进行:

Integer[] r = itemSet.toArray(a-> {
    Integer[] v = new Integer[a];
    Arrays.setAll(v,i->v[i]*2);
    return v;
});
System.out.println(Arrays.toString(r));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多