Reputation: 65
I have solved the problems from the Java book, and I have some questions.
In the code below, I want to create a new stream by doubling each element using the map intermediate operation. And I want to print a new stream to get the sum of all the elements except the number less than 50 in the generated stream.
How can i solve this ??
package test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.util.Optional;
import java.util.stream.IntStream;
public class tt {
public static void main(String[] args) {
try {
Stream <String> lines = Files.lines(Paths.get("C:\\Users\\wonheelee\\eclipse-workspace\\test\\stream-data.txt"));
IntStream IS = lines.mapToInt(Integer::valueOf);
IS.forEach(System.out::println);
lines.close();
} catch (IOException e) {
// No action
}
}
}
Upvotes: 0
Views: 593
Reputation: 17890
Here you go..
int result = lines
.mapToInt(Integer::parseInt)
.map(element -> element * 2) //Double
.filter(element -> element >= 50) //Filter out values less than 50
.sum(); //sum
You can combine the mapToInt
and map
in one mapToInt
itself
.mapToInt(element -> Integer.parseInt(element) * 2)
Also, note as Aomine@ mentioned in the comments, using Integer.parseInt
to avoid an extra boxing/unboxing.
I'm not quite sure what you mean by create a new stream. You can get a new Stream by calling Files.lines
again.
You cannot reuse a Stream once it is already consumed.
Reference:
Is there any way to reuse a Stream?
Upvotes: 2