Creating a list with repeating element

后端 未结 5 522
一生所求
一生所求 2020-12-29 01:00

Is there an utility method in Java that generates a list or array of a specified length with all elements equal to a specified value (e.g [\"foo\", \"foo\", \"foo\", \"foo\"

5条回答
  •  悲&欢浪女
    2020-12-29 01:07

    Using IntStream, you can generate a range of integers, map them to the element you want and collect it as a list.

    List list = IntStream.rangeClosed(0, 5)
                .mapToObj(i -> "foo")
                .collect(Collectors.toList());
    

    Or, as an array

     String[] arr = IntStream.rangeClosed(0, 5)
                .mapToObj(i -> "foo")
                .toArray(String[]::new);
    

提交回复
热议问题