5

There are numerous ways to do this, but using Java 8 streams (likely IntStream), how can I produce a dummy string that is N characters long?

I've seen examples using IntStream.range(), and the various aggregator functions (sum, average), but I don't see a way to do this.

My first random guess looks like this:

IntStream.range(1, 110).map(i -> "x").collect(Collectors.joining());

But that's wrong in a couple of different ways.

David M. Karr
  • 14,317
  • 20
  • 94
  • 199

3 Answers3

7

You need to use mapToObj() and not map() as you actually use an IntStream and IntStream.map() takes as parameter an IntUnaryOperator, that is an (int->int) function.

For same character dummy (for example "x") :

collect = IntStream.range(1, 110)
                   .mapToObj(i ->"x")
                   .collect(Collectors.joining());

Form random dummy :

You could use Random.ints(long streamSize, int randomNumberOrigin, int randomNumberBound).

Returns a stream producing the given streamSize number of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).

To generate a String containing 10 random characters between the 65 and 100 ASCII code :

public static void main(String[] args) {
    String collect = new Random().ints(10, 65, 101)
                                 .mapToObj(i -> String.valueOf((char) i))
                                 .collect(Collectors.joining());

    System.out.println(collect);

}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
4

If you really want to use a Stream for this, you can utilize Stream#generate, and limit it to n characters:

Stream.generate(() -> "x").limit(110).collect(Collectors.joining());
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
2

You are actually almost there:

String s = IntStream.range(40, 110)
                    .mapToObj(i -> Character.toString((char)i))
                    .collect(Collectors.joining());

System.out.println(s);

Produces:

()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklm

If you want random ordering, with N = 60 for instance:

Random r = new Random();    

IntStream.generate(() -> 40 + r.nextInt(70))
         .limit(60)
         .mapToObj(i -> Character.toString((char)i))
         .collect(Collectors.joining()));

Produces

Z>fA+5OY@:HfP;(L:^WKDU21T(*1//@V,F9O-SA2;+),A+V/mLjm<eaE56CH
Alexandre Dupriez
  • 3,026
  • 20
  • 25