Simple way to repeat a string

后端 未结 30 3087
清酒与你
清酒与你 2020-11-21 06:55

I\'m looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid f

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 07:00

    With java-8, you can also use Stream.generate.

    import static java.util.stream.Collectors.joining;
    ...
    String repeated = Stream.generate(() -> "abc").limit(3).collect(joining()); //"abcabcabc"
    

    and you can wrap it in a simple utility method if needed:

    public static String repeat(String str, int times) {
       return Stream.generate(() -> str).limit(times).collect(joining());
    }
    

提交回复
热议问题