检查自定义对象列表是否与 Java 8 中的属性具有相同的值 [英] Check whether list of custom objects have same value for a property in Java 8

查看:29
本文介绍了检查自定义对象列表是否与 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 中的属性具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆