簡體   English   中英

如何根據 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的時間復雜性containsO(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM