How to Generate a Stream from a String

How do I generate a stream from a string?


public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}

Don't forget to use Using:

using (var stream = GenerateStreamFromString("a,b \n c,d"))
{
// ... Do stuff to stream
}

About the StreamWriter not being disposed. StreamWriter is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. The Dispose method will close the underlying Stream that StreamWriter is writing to. In this case that is the MemoryStream we want to return.

In .NET 4.5 there is now an overload for StreamWriter that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.

See Is there any way to close a StreamWriter without closing its BaseStream?

create stream from string directly

You can use Stream.of which returns a sequential Stream containing a single element.

Stream<String> stream = Stream.of(x);

How can I create a Stream String[] with only one element with Stream.of?


Solution

Stream<String[]> stream = Stream.<String[]>of(tropicalFruits);

or

Stream<String[]> stream = Stream.of(new String[][]{tropicalFruits});

Explanation

To produce a Stream<T>, Stream.of takes either T or T....

A T[] parameter perfectly applies to the second signature.

Therefore, passing a String[] invokes the Stream.of(String...) version.

To change this behaviour, we need to provide some extra information about T (1) or define it more clearly (=unambiguously) (2).

There are two ideas came to my mind:

  1. To specify a type argument of the method explicitly to use the first signature.

    Stream.<String[]>of(new String[]{}) will produce a Stream<String[]>.
  2. To wrap a T[] value in a T[][] array to use the second signature.

    Stream.of(new String[][]{}) will produce a Stream<String[]>.

Produce a dummy string N characters long with java 8 streams

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);

}

How to create streams from string in Node.Js?

From node 10.17, stream.Readable have a from method to easily create streams from any iterable (which includes array literals):

const { Readable } = require("stream")

const readable = Readable.from(["input string"])

readable.on("data", (chunk) => {
console.log(chunk) // will be called once with `"input string"`
})

Note that at least between 10.17 and 12.3, a string is itself a iterable, so Readable.from("input string") will work, but emit one event per character. Readable.from(["input string"]) will emit one event per item in the array (in this case, one item).

Also note that in later nodes (probably 12.3, since the documentation says the function was changed then), it is no longer necessary to wrap the string in an array.

https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options

Create a Stream Character from a Stream String

From the answer here:

Stream<String> foo = ...
Stream<Character> characters = foo.flatMap(x -> x.chars().mapToObj(i -> (char) i));

or

Stream<Character> characters = foo.flatMapToInt(CharSequence::chars)
.mapToObj(i -> (char) i);

Just use flatMap or flatMapToInt.

Converting String to Stream

You can use the following piece of code....

byte[] bytes = Convert.FromBase64String(stringinput);
MemoryStream stream = new MemoryStream(bytes);
IInputStream is=stream.AsRandomAccessStream(); //It will return an IInputStream object

How to convert Stream String[] to Stream String ?


<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

A Stream#flatMap mapper expects a Stream to be returned. You are returning a String[]. To turn a String[] into a Stream<String>, use Arrays.stream(a.split(" ")).

The complete answer to your assignment:

public static Map<Integer, List<String>> wordsByLength(String file)
throws IOException {
return Files.lines(Paths.get(file))
.flatMap(a -> Arrays.stream(a.split("\\s+")))
.collect(Collectors.groupingBy(String::length));
}


Related Topics



Leave a reply



Submit