Creating a list with repeating element

后端 未结 5 536
一生所求
一生所求 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:15

    For an array you can use Arrays.fill(Object[] a, Object val)

    String[] strArray = new String[10];
    Arrays.fill(strArray, "foo");
    

    and if you need a list, just use

    List asList = Arrays.asList(strArray);
    

    Then I have to use two lines: String[] strArray = new String[5]; Arrays.fill(strArray, "foo");. Is there a one-line solution?

    You can use Collections.nCopies(5, "foo") as a one-line solution to get a list :

    List strArray = Collections.nCopies(5, "foo");
    

    or combine it with toArray to get an array.

    String[] strArray = Collections.nCopies(5, "foo").toArray(new String[5]);
    

提交回复
热议问题