简体   繁体   中英

how can I reduce my list of structures based on the other list of Strings in Java?

In my Java application I have a class:

public class MyStructure {

    SomeClass someClass;
    String[] fields;

    ...
}

Now, I have a list of the structures above:

List< MyStructure> structures = getStructures();

I also have a list of Strings:

List<String> myList = getStrings();

I need to filter the first list ( structures ) so that it only contains elements, that in their fields array contain any of the Strings present on myList .

I thought about writing a for loops, something like:

List<MyStructure> outcomeStructures = new ArrayList<>(); 

for (MyStructure mystructure : structures) {
    for (String temp : mystructure.getFields()) {
        if (myList.contains(temp) {
            outcomeStructures.add(mystructure);
        }
    }
}

but maybe there's a better way to do so? Thanks!

For the better performance you can convert the List<String> myList = getStrings(); to Set<String> mySet since HashSet time complexity for contains is O(1) always. Then use:

List<MyStructure> outcomeStructures = structures.stream()
        .filter(st -> Arrays.stream(st.getFields()).anyMatch(mySet::contains))
        .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM