Check whether list of custom objects have same value for a property in Java 8

Joy :

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?

Sweeper :

One way is to get the name of the first list and call allMatch and check against that.

String firstName = yourListOfAs.get(0).name;
boolean allSameName = yourListOfAs.stream().allMatch(x -> x.name.equals(firstName));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=432230&siteId=1