2

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!

Naman
  • 27,789
  • 26
  • 218
  • 353
randomuser1
  • 2,733
  • 6
  • 32
  • 68

1 Answers1

3

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());
Naman
  • 27,789
  • 26
  • 218
  • 353
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • I think there's some problem, the collect function is not visible here, perhaps I should call it on something else than the result of anyMatch, that returns boolean? – randomuser1 Feb 17 '20 at 22:47
  • @randomuser1 Did you make sure the brackets put in the code are appropriately matched? Try out the current code, I can confirm it compiles successfully. – Naman Feb 18 '20 at 05:09