Reputation: 2935
I'll generate for each line from an input file a Foo object and save in the next step all the objects in the database (Spring Data JPA).
//read file into stream
try (Stream<String> stream = Files.lines((path), Charset.forName("ISO-8859-1"))) {
Stream<Foo> rStream = stream.map(line -> new Foo(line));
rStream.forEach(line -> fooRepository.save(line));
} catch (IOException e) {
e.printStackTrace();
}
I received an Unhandled exception: java.lang.Exception
, because the constructor of the Foo class can propagate an exception from the MyParser class:
public Foo(String row) throws Exception {
String split[] = StringUtils.split(row, "Ú");
field = MyParser.getInt(split[0]);
}
Is it possible to use the Java stream API anyway? Maybe with only one awesome stream? Somethings like this:
stream.map(Foo::new).forEach(foo -> fooRepository.save(foo));
I use Java 8 with Spring Boot 1.5.8.
Upvotes: 1
Views: 76
Reputation: 120978
If you can edit the class, why not simply throw a RuntimeException
instead of throwing an Exception
. If the API that you use still throws Exception
you can just wrap it into:
catch(Exception e){
throw new RuntimeException(e);
}
Then you can simplify it to :
stream.map(Foo::new).forEach(fooRepository::save)
Upvotes: 4