[英]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.