在我的 Java
应用程序中,我有一个类:
public class MyStructure {
SomeClass someClass;
String[] fields;
...
}
现在,我有了上述结构的列表:
List< MyStructure> structures = getStructures();
我还有一个字符串列表:
List<String> myList = getStrings();
我需要过滤第一个列表(结构
),以便它只包含元素,在其字段
数组中包含myList上存在的任何字符串
.
我考虑过编写一个 for 循环,例如:
List<MyStructure> outcomeStructures = new ArrayList<>();
for (MyStructure mystructure : structures) {
for (String temp : mystructure.getFields()) {
if (myList.contains(temp) {
outcomeStructures.add(mystructure);
}
}
}
但也许有更好的方法呢?谢谢!
最佳答案
为了获得更好的性能,您可以将 List<String> myList = getStrings();
转换为 Set<String> mySet
,因为 contains
的 HashSet time complexity 始终是 O(1)
。然后使用:
List<MyStructure> outcomeStructures = structures.stream()
.filter(st -> Arrays.stream(st.getFields()).anyMatch(mySet::contains))
.collect(Collectors.toList());
关于java - 如何根据 Java 中的其他字符串列表减少结构列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270933/