在我的Java
应用程序中,有一个类:
public class MyStructure {
SomeClass someClass;
String[] fields;
...
}
现在,我有以上结构的列表:
List< MyStructure> structures = getStructures();
我也有一个字符串列表:
List<String> myList = getStrings();
我需要过滤第一个列表(structures
),以便它仅包含元素,在它们的fields
数组中包含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
,因为HashSet time complexity的contains
始终为O(1)
。然后使用:
List<MyStructure> outcomeStructures = structures.stream()
.filter(st -> Arrays.stream(st.getFields()).anyMatch(mySet::contains))
.collect(Collectors.toList());