This question already has an answer here:
Modify file using Files.lines
(1 answer)
Closed 7 years ago.
Suppose I have a java.util.stream.Stream of objects with some nice toString method:
What's the shortest/most elegant solution to write this stream to a file, one line per stream element?
For reading, there is the nice Files.lines method, so I thought there must be a symmetric method for writing to file, but could not find one.
Files.write only takes an iterable.
Probably the shortest way is to use Files.write along with the trick which converts the Stream to the Iterable:
Files.write(Paths.get(filePath), (Iterable<String>)stream::iterator);
For example:
Files.write(Paths.get("/tmp/numbers.txt"),
(Iterable<String>)IntStream.range(0, 5000).mapToObj(String::valueOf)::iterator);
If it looks too hackish, use more explicit approach:
try(PrintWriter pw = new PrintWriter(Files.newBufferedWriter(
Paths.get("/tmp/numbers.txt")))) {
IntStream.range(0, 5000).mapToObj(String::valueOf).forEach(pw::println);
}
If you have stream of some custom objects, you can always add the .map(Object::toString) step to apply the toString() method.
Related
This question already has answers here:
Java 8 Stream IllegalStateException: Stream has already been operated on or closed
(6 answers)
Closed 4 years ago.
Why is the following java 8 code showing a bug at the second call to get()?
Stream<String> aStream = Stream.concat(Stream.of("A"), Stream.of("B"));
String a = stream.findFirst().get();
String b = stream.findFirst().get();
The "aStream" stream should see two values: "A" and "B". However, trying to read anything, after the first element has already been consumed, gives
java.lang.IllegalStateException: stream has already been operated upon or closed
Isn't it a bug in Java 8? First, why doesn't a consumed Stream.of()-created stream return an Optional with isPresent()==false? Second, why doesn't Stream.concatenate() correctly concatenate such Stream.of()-created streams?
Stream.concatenate() does concatenate the two Streams. However, once you execute a terminal operation of the combined Stream - stream.findFirst() - you can't do anything else with that Stream. You can only run one terminal operation of a Stream. That's why it's called "terminal".
If you want to obtain more than one element of the combined Stream, use a different terminal operation, such as collect:
List<String> list = stream.collect(Collectors.toList());
To clarify, the combined Stream is a single Stream<String>, not a Stream of Streams. Therefore findFirst() consumes the entire combined Stream, not just the first Stream that was uses to create the combined Stream.
Because Stream.findFirst() is a terminal operation, and terminal operations can only be run once on a given stream.
This question already has answers here:
What is difference between Collection.stream().forEach() and Collection.forEach()?
(5 answers)
Closed 5 years ago.
Starts from java 8 to iterate throug list I can use both:
List list = new ArrayList();
1. list.forEach(...)
2. list.stream().forEach(...)
Is it any advantages of using second case? To convert list to stream?
There are no advantages of using the second case, unless you have a parallel stream. There is a disadvantage, namely that Stream.forEach() doesn't guarantee to respect encounter order. A more accurate (but still unnecessary) equivalent would be Stream.forEachOrdered().
No, in theory, the second option is worse than the first one - you pay the cost of instantiation/garbage-collection and calling a Stream instance and don't really get any benefit in return.
Additionally, in theory the iteration order of Stream.forEach() isn't deterministic.
This question already has answers here:
Find first element by predicate
(8 answers)
Closed 8 years ago.
With Java 8+, you can easily find all elements of a collection that match a Predicate.
someCollection.stream().filter(somePredicate)
You could then find the first element:
someCollection.stream().filter(somePredicate).findFirst()
The problem with this, though, is that it runs the Predicate against all the elements. Is there a clean way to only run the Predicate against elements until the first match is found, and then return it, like anyMatch does (but returns a boolean telling if one was found)?
It does exactly what you want. It doesn't run over all the elements. The filter method creates a stream and on top of it findFirst creates another stream.
So when you try to get the element of the stream that was created after findFirst() you'll get only the first one that matches the predicate.
Best way to check that is to add a print line or something like that inside the predicate.
Create a stream of integers for example from 0 to 10 and create a predicate that prints the number and then checks if it's divided by 3. You'll get this printed out: 0, 1, 2, 3 and that's it.
I wrote a question + answer in the past to explain in more details how it works: Understanding java 8 stream's filter method
This question already has answers here:
I want to print any text without using Print function in java?
(5 answers)
Closed 8 years ago.
I have no idea how to start writing a java code to print
a string without using any inbuilt function like println etc.
Does anyone know how to write it?
I will not paste you all the article you can read here: http://luckytoilet.wordpress.com/2010/05/21/how-system-out-println-really-works/
But read it and look the repetition of "native" word.
Then you can jump to this other post : What is a native implementation in Java?
Then, you will have the presumption that you cannot write to process standard stream (or error) without using any native function, because you need something runnable on different OS... and that's the goal of the JVM.
You can write it using PrintWriter class
PrintWriter printWriter = new PrintWriter(System.out);
printWriter.write("Hello");
printWriter.flush();
printWriter.close();
This question already has answers here:
Get an OutputStream into a String
(6 answers)
Closed 9 years ago.
I think this has been answered but I can't seem to find it.
I have an instance method which writes some contents to an output stream
writeTo(OutputStream){
//class specific logic
}
I want it to get these contents into a StringBuilder. I can do this via a temporary file but that does not seem right. I want to do something like:
Stringbuilder sb = /* */;
OutputStream os = outForStringBuilder(sb);//not sure how to do this
instance.writeTo(os); //This should write the contents to Stringbuilder
Use a ByteArrayOutputStream and then call toString(charSet) - no need for a StringBuilder.
So you are wanting output written to the stream to go to a StringBuffer instead. I am assuming you are doing this because an OutputStream is required somewhere else. You could use ByteArrayOutputStream, but if you want to preserve the StringBuffer behavior, you might simply wrap a StringBuffer in a subclass of OutputStream like the code here:
http://geronimo.apache.org/maven/specs/geronimo-javamail_1.4_spec/1.6/apidocs/src-html/org/apache/geronimo/mail/util/StringBufferOutputStream.html#line.31