![](/img/trans.png)
[英]How I can determine if there is another element after the current one or not in java using list Structures in java
[英]how can I reduce my list of structures based on the other list of Strings in Java?
在我的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的时间复杂性为contains
是O(1)
总是。 然后使用:
List<MyStructure> outcomeStructures = structures.stream()
.filter(st -> Arrays.stream(st.getFields()).anyMatch(mySet::contains))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.