java - Java 8流:将逗号分隔的字符串转换为抽象枚举列表
问题描述
java.lang.Enum
是否可以使用流将逗号分隔的字符串转换为列表?
我的原始代码如下,它正在工作:
List<String> inValuesStr = Arrays.asList(criteria.getValue().toString().split(","));
List<Enum> inValues = new ArrayList<>();
for (String val : inValuesStr){
inValues.add(Enum.valueOf(path.getType(),val));
}
我试图将其重构为如下代码:
List<Enum> inValues = Arrays.stream(criteria.getValue().toString().split(","))
.map(v -> Enum.valueOf(path.getType(),v))
.collect(Collectors.toList());
看起来很基本......但是,显示了以下编译时错误:
Error:(--, --) java: incompatible types: java.lang.Object cannot be converted to java.util.List<java.lang.Enum>
我无法理解错误在哪里。有人有同样的经历吗?感谢分享解决方案。
解决方案
这对我来说很好:
enum Ascii {
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z;
}
private void test() throws InterruptedException {
List<String> inValuesStr = Arrays.asList("A,B,C,D,E,F,G,H,I,J,K,L,M,N".split(","));
List<Ascii> list = inValuesStr.stream()
.map(s -> Ascii.valueOf(s))
.collect(Collectors.toList());
}
推荐阅读
- c# - 基础数学程序抛出系统空异常
- reactjs - React 编写的应用程序中的状态信息通常存储在哪个库中?
- php - 在 laravel 的 AppServiceProvider 中使用身份验证
- html - 如何并排显示div元素
- ruby-on-rails - ActionController::Parameters 将整数转换为字符串
- python - Python concurrent.futures:ProcessPoolExecutor 无法工作
- lua - Prosody 在更新到 Debian Buster 后拒绝连接到 MySQL 数据库
- android - 使用openCV从照片中检测二维码问题
- octave - 限制大型矩阵的 Octave 控制台输出
- javascript - 为什么我不能在 React/Redux 中索引我的对象?TypeError:无法读取未定义的属性“1”