根据枚举列表验证字符串列表

时间:2019-02-20 13:15:30

标签: java enums

我有一个.properties文件,其中包含一组属性作为键值对。这被读入配置Enum类。此配置类包含与属性对应的枚举。我希望能够发现两者之间的差异。因此,如果属性文件包含类中不存在的属性,或者相反。

换句话说,我有一个枚举数组:

MyEnumClass[] enums = {E1,E2,E3}

和代表枚举的字符串数组

String[] properties = {"E1","E2","E3"}

如何找到两者的交点?最好是我想避免流。

2 个答案:

答案 0 :(得分:2)

这是计算交点的简单方法(更改输入以使结果显而易见):

List<String> properties = Arrays.asList(new String[] { "E1", "E2" });
List<MyEnumClass> enums = Arrays.asList(new MyEnumClass[] 
                          { MyEnumClass.E2, MyEnumClass.E3 });

List<String> enumNames = new ArrayList<>();
for (MyEnumClass e : enums)
    enumNames.add(e.name());

List<String> intersection = new ArrayList<>(enumNames);
intersection.retainAll(properties);
System.out.println(intersection); //[E2]

这可以计算彼此之间的差异:

List<String> propDiff = new ArrayList<>(properties);
propDiff.removeAll(enumNames);
System.out.println(propDiff); //[E1]

List<String> enumDiff = new ArrayList<>(enumNames);
enumDiff.removeAll(properties);
System.out.println(enumDiff); //[E3]

答案 1 :(得分:0)

您可以像这样使用EnumSet<MyEnumClass>

Set<MyEnumClass> all = EnumSet.allOf(MyEnumClass.class);

然后从您的属性中创建另一个EnumSet<MyEnumClass>

Set<MyEnumClass> loaded = EnumSet.noneOf(MyEnumClass.class);
for(String property : properties) {
    loaded.add(MyEnumClass.valueOf(property));
}

然后您可以使用Collection.removeAllCollection.addAllCollection.retainAll检查其他内容:

// all will now contain every element from loaded
all.addAll(loaded);
// all will now contain every element which was not contained in loaded
all.removeAll(loaded);
// all will now contain every element which was contained in loaded
all.retainAll(loaded);