首页 > 解决方案 > 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>

我无法理解错误在哪里。有人有同样的经历吗?感谢分享解决方案。

标签: javalistintellij-ideaenumsjava-stream

解决方案


这对我来说很好:

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());
}

推荐阅读