I have a list of Foo objects, where each Foo contains a name and a List<Strings>.
I am trying to
- find if the fooList contains a Foo object with a target name, and if such element exists,
- find if a target set of strings is a subset of the List stringList in the found Foo instance.
This is the code I have yet.
import java.util.List;
public class Foo {
String fooName;
List<String> bars;
public Foo(String fooName, List<String> bars) {
this.fooName = fooName;
this.bars = bars;
}
public String getFooName() {
return fooName;
}
public List<String> getBars() {
return bars;
}
}
@Test
public boolean demo() {
List<Foo> fooList = new ArrayList<>();
// add foos and bars
String fooNameToFind = "some-target-name";
Set<String> barsToFind = new HashSet<>();
// add to list of target bar names
Optional<Foo> optionalFoo = fooList.stream()
.filter(foo -> foo.getFooName().equals(fooNameToFind))
.findFirst();
if (optionalFoo.isEmpty()) {
// have to log something here
Logger.getAnonymousLogger().info("target foo not found");
return false;
}
boolean success = optionalFoo.get().getBars().stream()
.filter(barsToFind::remove)
.anyMatch(__ -> barsToFind.isEmpty());
if (!success) {
Logger.getAnonymousLogger().info("no match for list of bar names for given foo name");
}
return success;
}
I wish to log whenever I don't find either the target name or the list subset. As you can see, I am currently using .isEmpty() and .get(), which I want to avoid. Please let me know if there is a better way to chain these.
TIA
EDIT: How about using peek?