问题描述
我是 Java 8 的新手.我有一个类型为 A 的自定义对象列表,其中 A 如下所示:
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;
}
我想确定该列表中的所有对象是否都具有相同的名称.我可以通过迭代列表并捕获名称的先前和当前值来实现.在这种情况下,我发现 如何计算列表中具有相同属性值的自定义对象的数量.但是有没有更好的方法在 java 8 中使用流来做同样的事情?
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?
推荐答案
一种方法是获取第一个列表的名称并调用 allMatch
并进行检查.
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));
这篇关于检查自定义对象列表对于 Java 8 中的属性是否具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!