vavr_使用Vavr在Java 8流中更好的异常处理

vavr

by Rajasekar Elango

由Rajasekar Elango

In this post, I will provide tips for better exception handling in Java 8 streams using the Functional Java library Vavr.

在这篇文章中,我将提供使用Functional Java库Vavr在Java 8流中更好地处理异常的技巧。

问题 (The problem)

To illustrate with an example, let’s say we want to print the day of the week for a given stream of date strings in the format MM/dd/YYYY.

为了举例说明,假设我们要以MM/dd/YYYY格式打印给定日期字符串流的星期几。

初始解决方案 (Initial solution)

Let’s start with an initial solution, as seen below, and iteratively improve on it.

让我们从一个初始解决方案开始,如下所示,然后对其进行迭代改进。

This will output

这将输出

Huh, if a date string is invalid, this fails at the first DateTimeParseException without continuing with valid dates.

呵呵 ,如果日期字符串是无效的,这未能在第一DateTimeParseException没有与有效日期继续。

Java 8抢救之选 (Java 8 Optional to the rescue)

We can refactor parseDate to return Optional<LocalDate> to make it discard invalids and continue processing valid dates.

我们可以重构parseDate以返回Optional<LocalDa te>,以使其放弃无效值并继续处理有效日期。

This will skip errors and converts all the valid dates.

这将跳过错误并转换所有有效日期。

WEDNESDAY Text '01-01-2015' could not be parsed at index 2 THURSDAY Text 'not a date' could not be parsed at index 0 FRIDAY

This is a great improvement, but the exception has to be handled within the parseDate method and can’t be passed back to the main method to deal with it. We can’t make the parseDate method throw a checked exception as the Streams API doesn’t play well with methods that throw exceptions.

这是一个很大的改进,但是必须在parseDate方法中处理异常,并且不能将其传递回main方法进行处理。 我们不能使parseDate方法抛出检查异常,因为Streams API与抛出异常的方法不能很好地配合使用。

Vavr的Try Monad更好的解决方案 (A better solution with Vavr’s Try Monad)

Vavr is a functional library for Java 8+. We will use the Try object from Vavr, which can be either an instance of Success or Failure. Basically Try is a monadic container type which represents a computation that may either result in an exception, or return a successfully computed value. Here is the modified code using Try:

Vavr是Java 8+的功能库。 我们将使用Vavr中的Try对象,该对象可以是SuccessFailure的实例。 基本上, Try是一种Monadic容器类型,它表示可能导致异常或返回成功计算值的计算。 这是使用Try修改的代码:

The output is

输出是

WEDNESDAY Failed due to Text '01-01-2015' could not be parsed at index 2 THURSDAYFailed due to Text 'not a date' could not be parsed at index 0 FRIDAY

Now the exception is passed back to main to deal with it. Try also has APIs to implement recovery logic or return a default value in case of error.

现在,异常被传递回main进行处理。 Try还提供API来实现恢复逻辑或在出现错误的情况下返回默认值。

To demonstrate this, let’s say we also want to support MM-dd-YYYY as an alternate string format for dates. The below example shows how we can easily implement recovery logic.

为了说明这一点,假设我们还希望支持MM-dd-YYYY作为日期的备用字符串格式。 以下示例显示了我们如何轻松实现恢复逻辑。

The output shows that now the date 01-01-2015 is also successfully converted.

输出显示,现在日期01-01-2015也已成功转换。

WEDNESDAY THURSDAY THURSDAY Failed due to Text 'not a date' could not be parsed at index 0 FRIDAY

So Try Monad can be used to elegantly deal with exceptions and fail fast on errors.

因此, Try Monad可以用于优雅地处理异常,并在发生错误时快速失败

Update on 12/03/2018:

2018年12月3日更新:

The code examples are updated to use Doculet.

代码示例已更新为使用Doculet 。

Originally published at http://erajasekar.com/posts/better-exception-handling-java8-streams-using-javaslang/.

最初发布在http://erajasekar.com/posts/better-exception-handling-java8-streams-using-javaslang/中 。

翻译自: https://www.freecodecamp.org/news/better-exception-handling-in-java-8-streams-using-vavr-6eda31285ce9/

vavr

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394019.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python-strace命令追踪ssh操作

Python-strace命令追踪ssh操作 通过strace 命令追踪ssh的进程ID&#xff0c;记录操作的命令[实际上是内核里面记录的东西]&#xff0c;进行操作日志的Py解析达到效果 追踪进程并写入ssh操作到文件中 Ps: 此时机器A已经ssh登录了机器B&#xff0c;取得它的ssh进程PID 机器A登录后…

java h2 derby_嵌入式H2数据库的Spring配置以进行测试

小编典典由于我不知道是否有任何工具可以检查数据库&#xff0c;我认为一个简单的解决方案是使用支持HSQL&#xff0c;H2和Derby 的Spring嵌入式数据库(3.1.x docs&#xff0c;current docs)。 。使用H2&#xff0c;你的xml配置如下所示&#xff1a;如果你更喜欢基于Java的配置…

基础的python程序_Python程序入门

Python语法元素入门Python语法元素分析注释注释&#xff1a;程序员在代码中加入的说明信息&#xff0c;不被计算机执行注释的两种方法&#xff1a;单行注释以#开头多行注释以开头和结尾# Here are the commentsThis is a multiline commerntused in Python缩进1个缩进 &#xf…

解决阿里云服务器磁盘报警

一般磁盘报警涉及到实际磁盘和inode文件索引节点 1.df -h检查磁盘占用不高 2.df -i检查inode文件索引节点有一个挂载目录达到89%,里面有一个目录产生大量的4k大的缓存文件,删除该目录下的文件解决: 删除该目录下小于4kb的文件 find /data/tmp -type f -size -4 -exec rm -rf {}…

leetcode310. 最小高度树(bfs)

对于一个具有树特征的无向图&#xff0c;我们可选择任何一个节点作为根。图因此可以成为树&#xff0c;在所有可能的树中&#xff0c;具有最小高度的树被称为最小高度树。给出这样的一个图&#xff0c;写出一个函数找到所有的最小高度树并返回他们的根节点。格式该图包含 n 个节…

如何构建自己的免费无服务器评论框

by Shaun Persad通过Shaun Persad 如何构建自己的免费无服务器评论框 (How you can build your own free, serverless comment box) Contentful’s flexible content modeling goes far beyond blog posts. Here’s how you can leverage Contentful and Netlify to create a …

[Swift]LeetCode1035.不相交的线 | Uncrossed Lines

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号&#xff1a;山青咏芝&#xff08;shanqingyongzhi&#xff09;➤博客园地址&#xff1a;山青咏芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;➤GitHub地址&a…

BZOJ1054(搜索)

大力搜&#xff0c;状态用一个16位的数字表示。 1 #include <bits/stdc.h>2 3 using namespace std;4 5 #define rep(i,a,b) for(int i(a); i < (b); i)6 7 const int A 30 1;8 9 struct node{int x, y; } op[A]; 10 struct Nod…

php sql语句过滤,php如何做sql过滤

php如何做sql过滤SQL注入攻击指的是通过构建特殊的输入作为参数传入Web应用程序&#xff0c;而这些输入大都是SQL语法里的一些组合&#xff0c;通过执行SQL语句进而执行攻击者所要的操作&#xff0c;其主要原因是程序没有细致地过滤用户输入的数据&#xff0c;致使非法数据侵入…

ajaxfileupload 返回值_ajaxFileUpload上传文件返回json无法解析

最近做一个文件上传的功能&#xff0c;还要绑定数据传输到后台&#xff0c;为了不影响前端的体验&#xff0c;采用ajax发送请求。找了一些资料&#xff0c;网上的用ajaxupload这个插件。但是无论成功还是失败都是执行的error的回调函数。后台我采用springmvc返回的json&#xf…

leetcode133. 克隆图(bfs)

给你无向 连通 图中一个节点的引用&#xff0c;请你返回该图的 深拷贝&#xff08;克隆&#xff09;。 图中的每个节点都包含它的值 val&#xff08;int&#xff09; 和其邻居的列表&#xff08;list[Node]&#xff09;。 class Node { public int val; public List neighbor…

OSCON上最受欢迎的Docker演讲

本文讲的是OSCON上最受欢迎的Docker演讲&#xff0c;【编者的话】本文介绍了上个月OSCON大会有关Docker最受欢迎的一个分享&#xff1a;真实线上环境的Docker技巧。分享者是一名运维工程师叫Bridget&#xff0c;她所在的公司DramaFever在2013年10月开始在线上环境部署使用Docke…

测试驱动开发 测试前移_测试驱动开发:它是什么,什么不是。

测试驱动开发 测试前移by Andrea Koutifaris由Andrea Koutifaris Test driven development has become popular over the last few years. Many programmers have tried this technique, failed, and concluded that TDD is not worth the effort it requires.在过去的几年中&…

【C/C++开发】C++库大全

C特殊限定符(1)--static 当static来修饰类数据成员时&#xff0c;这个类的所有对象都可以访问它。因为值在内存中持续存在&#xff0c;它可以被对象有效共享。这意味着当一个对象改变static数据成员的值时&#xff0c;就改变了所有对象的这个数据成员的值。 定义一个类: class …

java二维数组水平翻转,C 语言 利用二维数组实现对输入的数组进行翻转

C 语言 利用二维数组实现对输入的数组进行翻转(帮助理解对图像翻转编辑原理)/*?输入几行几列数字和翻转方式&#xff0c;如&#xff1a;3 4 0即代表3行4列&#xff0c;左右翻转&#xff1b;6 5 1即代表6行5列&#xff0c;上下翻转。输入示例&#xff1a;3 4 0________________…

lightgbm 保存模型 过大_一个例子读懂LightGBM的模型文件

机器学习模型的可解释性是个让人头痛的问题。在使用LightGBM模型的肯定对生成的GBDT的结构是好奇的&#xff0c;我也好奇&#xff0c;所以就解析一个LightGBM的模型文件看看&#xff0c;通过这个解析&#xff0c;你可以看懂GBDT的结构。另外&#xff0c;了解模型文件&#xff0…

Oracle Sql 胡乱记

/Oracle查询优化改写/ --1、coalesce 返回多个值中&#xff0c;第一个不为空的值 select coalesce(, , s) from dual; --2、order by -----dbms_random.value 生产随机数,利用随机数对查询结果进行随机排序 select * from emp order by dbms_random.value; --指定查询结果中的一…

leetcode752. 打开转盘锁(bfs)

你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字&#xff1a; ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ 。每个拨轮可以自由旋转&#xff1a;例如把 ‘9’ 变为 ‘0’&#xff0c;‘0’ 变为 ‘9’ 。每次旋转都只能旋转一个拨轮的一位…

Object Pools 喷泉效果实现

摘录自&#xff1a;http://catlikecoding.com/unity/tutorials/object-pools/ 工程 效果图 工程里面有响应的注释 源码我就不单独放出来了

从头学习计算机网络_我如何通过从头开始构建网络爬虫来自动进行求职

从头学习计算机网络它是如何开始的故事 (The story of how it began) It was midnight on a Friday, my friends were out having a good time, and yet I was nailed to my computer screen typing away.星期五是午夜&#xff0c;我的朋友们出去玩得很开心&#xff0c;但我被钉…