检查自定义对象列表是否与 Java 8 中的属性具有相同的值

2022-01-22 00:00:00 arraylist java-8 java java-stream

我是 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));

相关文章