Check whether list of custom objects have same value for a property in Java 8(检查自定义对象列表是否与 Java 8 中的属性具有相同的值)
问题描述
我是 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 中的属性具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查自定义对象列表是否与 Java 8 中的属性具有相同的值


- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01