繁体   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