为了账号安全,请及时绑定邮箱和手机立即绑定

如何从内联<填充列表<>?

如何从内联<填充列表<>?

慕田峪9158850 2022-09-28 15:58:22
我想用随机整数的元素填充List,范围为0到。为什么方法有效,无效?numberOfElementsnumberOfElements/10populateListStream1()populateListStream2()public static List<Integer> populateListStream1(int numberOfElements) {    return Stream.generate(new Random()::nextDouble)            .limit(numberOfElements)            .map(e -> (int)(e*numberOfElements/10))            .collect(Collectors.toList());}public static List<Integer> populateListStream2(int numberOfElements) {    return IntStream.range(0,numberOfElements)            .map(e -> random.nextInt(numberOfElements/10))            .collect(Collectors.toList());}
查看完整描述

3 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

在第二个示例中,该类中的 nextInt() 返回一个基元,该基元无法收集到 .添加一个调用,这会将 的 转换为它们的包装类:RandomintListboxedintInteger

public static List<Integer> populateListStream2(int numberOfElements){    return IntStream.range(0,numberOfElements)
                    .map(e -> random.nextInt(numberOfElements/10))
                    .boxed()
                    .collect(Collectors.toList());
}

但是第一个也通过铸造返回了原始的int!

是的,但它是在 中,所以它被自动装箱到.您可以通过运行以下操作来判断:StreamInteger

Stream.generate(new Random()::nextDouble)
        .limit(numberOfElements)
        .map(e -> (int)(e*numberOfElements/10))
        .peek(e -> System.out.println(e.getClass()))
        .collect(Collectors.toList());

哪些打印:

class java.lang.Integer

后者是.的好处之一是避免自动装箱和拆箱。除非您显式调用,否则它不会框IntStreamIntStreamboxed()


另请注意,Random 类中的一些方法已经返回随机数,如 ints() 和 doubles()


查看完整回答
反对 回复 2022-09-28
?
慕丝7291255

TA贡献1859条经验 获得超6个赞

第二个不起作用,因为您使用的是包含基元 int 类型的 IntStream。您必须在 之前致电盒装()。但更好的解决方案是使用 mapToObj() 而不是:map()map()

public static List<Integer> populateListStream2(int numberOfElements) { 
   return IntStream.range(0, numberOfElements)
            .mapToObj(e -> random.nextInt(numberOfElements / 10))
            .collect(Collectors.toList());
}

在这种情况下,值将像在方法中一样自动装箱。populateListStream2()

或者,我建议使用随机.ints() 来生成一个整数流。


查看完整回答
反对 回复 2022-09-28
?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

将其装入包装器对应的类 。另外,您可以尝试如下操作:intInteger


  public static List<Integer> populateListStream3(int numberOfElements) {

        List<Integer> listOfIntegers = new Random().ints(numberOfElements, 0, numberOfElements/10).boxed().collect(Collectors.toList());

        return listOfIntegers;

    }


查看完整回答
反对 回复 2022-09-28
  • 3 回答
  • 0 关注
  • 137 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号