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 中的属性具有相同的值
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
