I am new to Java 8. I have a list of custom objects of type A, where A is like below:
class A { int id; String name; }
I would like to determine if all the objects in that list have same name. I can do it by iterating over the list and capturing previous and current value of names. In that context, I found How to count number of custom objects in list which have same value for one of its attribute. But is there any better way to do the same in java 8 using stream?
The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same.
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
Stream findFirst() in Java with examples Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.
You can map
from A
--> String
, apply the distinct
intermediate operation, utilise limit(2)
to enable optimisation where possible and then check if count
is less than or equal to 1
in which case all objects have the same name and if not then they do not all have the same name.
boolean result = myList.stream() .map(A::getName) .distinct() .limit(2) .count() <= 1;
With the example shown above, we leverage the limit(2)
operation so that we stop as soon as we find two distinct object names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With