Skip to content
Advertisement

Java 8 find element matching in a list of objects where each object has another object

I have two classes:

JavaScript
JavaScript

I have a List<SampleClass> sampleClassList. I need to find the find element in the list which has a particular labelName and labelValue using Java 8.

If I need to get the SampleClass object based on testString I would do,

JavaScript

Now that the filtering involves Label class, I am unable to figure out how to do that. I have tried something like,

JavaScript

for which I get Bad return type in lambda expression: Optional<Label> cannot be converted to boolean. How would I go about making this change?

I could make it work by using contains() method

JavaScript

but would like to know if I can still use stream() to make this happen.

Advertisement

Answer

How about this? Instead of the suggested findFirst().isPresent() you can just use anyMatch()

JavaScript
JavaScript
JavaScript

This should print:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement