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
  • 21,685
  • 24
  • 196
  • 332
randomuser1
  • 2,655
  • 5
  • 30
  • 64

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
  • 21,685
  • 24
  • 196
  • 332
Deadpool
  • 33,221
  • 11
  • 51
  • 91
  • 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