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

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

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

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

和一个表示枚举的字符串数组

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

我怎样才能找到两者的交集?最好我想避免流。


HUX布斯
浏览 74回答 2
2回答

慕雪6442864

这是计算交集的简单方法(更改输入以使结果明显):List<String> properties = Arrays.asList(new String[] { "E1", "E2" });List<MyEnumClass> enums = Arrays.asList(new MyEnumClass[]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { MyEnumClass.E2, MyEnumClass.E3 });List<String> enumNames = new ArrayList<>();for (MyEnumClass e : enums)&nbsp; &nbsp; 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]

噜噜哒

你可以这样使用EnumSet<MyEnumClass>:Set<MyEnumClass> all = EnumSet.allOf(MyEnumClass.class);EnumSet<MyEnumClass>然后从您的属性创建另一个:Set<MyEnumClass> loaded = EnumSet.noneOf(MyEnumClass.class);for(String property : properties) {&nbsp; &nbsp; loaded.add(MyEnumClass.valueOf(property));}Collection.removeAll然后,您可以使用, Collection.addAll,来检查不同的内容Collection.retainAll:// all will now contain every element from loadedall.addAll(loaded);// all will now contain every element which was not contained in loadedall.removeAll(loaded);// all will now contain every element which was contained in loadedall.retainAll(loaded);&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java