Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the method with Java 8 streams?

Tags:

java

java-8

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!

like image 549
Artem Shpykuliak Avatar asked Jun 27 '18 12:06

Artem Shpykuliak


People also ask

What are the methods in streams in Java 8?

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.

How do I reuse a stream in Java 8?

In Java 8, Stream cannot be reused, once it is consumed or used, the stream will be closed.

Does Java 8 support streams?

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.

What is stream () method in Java?

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.


2 Answers

All you need is just Collections.nCopies

private static String assembleString(int numberOfCharacters, char character) {
    return String.join("",
            Collections.nCopies(numberOfCharacters, String.valueOf(character))
    );
}
like image 104
YCF_L Avatar answered Oct 06 '22 17:10

YCF_L


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());
like image 24
Ousmane D. Avatar answered Oct 06 '22 16:10

Ousmane D.