It can be an obvious question but I am thinking how to replace the method below with java 8 streams.
private String assembleString(int numberOfCharacters, char character) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < numberOfCharacters; i++) {
        stringBuilder.append(character);
    }
    return stringBuilder.toString();
}
I am new in Java, so java 8 it is like an unexplored world for me.
Thank you!
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
In Java 8, Stream cannot be reused, once it is consumed or used, the stream will be closed.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
All you need is just Collections.nCopies
private static String assembleString(int numberOfCharacters, char character) {
    return String.join("",
            Collections.nCopies(numberOfCharacters, String.valueOf(character))
    );
}
                        You can use Stream.generate:
return Stream.generate(() -> String.valueOf(character))
              .limit(numberOfCharacters)
              .collect(Collectors.joining());
or IntStream.rangeClosed:
return IntStream.rangeClosed(1, numberOfCharacters)
                .mapToObj(n -> String.valueOf(character))
                .collect(Collectors.joining());
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With