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

前端 未结 5 914
逝去的感伤
逝去的感伤 2020-12-16 13:29

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 woul

5条回答
  •  渐次进展
    2020-12-16 13:57

    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.

提交回复
热议问题