如何检查List<Object>中的任何空字段?

huangapple go评论71阅读模式
英文:

How to check for any null field of Object in List<Object>?

问题

我有一个对象列表传递给方法如下

```java
Student s = new Student (name,age,branch, year); // 学生原型

public void log(List<Student> items) { }

在方法内部,我需要检查每个学生对象中是否有任何null值,并记录该特定属性的空值以及相应的学生对象。是否有其他方法来检查这个,而不是使用以下方式:

items.stream().anyMatch(item -> item.getAge() == null ? System.out.println());

在实际情况中,我的对象包含超过30个属性,如果其中任何属性为null,我想要记录该null属性及其对应的对象。


<details>
<summary>英文:</summary>

I have a list of Object passed to a method as below.

```java
Student s = new Student (name,age,branch, year); // student prototype

public void log(List&lt;Student&gt; items) { }

Inside the method, I need to check for any null values in each student object and log that particular attribute which was null and the corresponding student object. Is there a way to check this other than using?:

items.stream().anyMatch(item -&gt; item.getAge() == null ? System.out.println());

In actual scenario, my object contains more than 30 attributes and if any of the attribute is null, I want to log that null attributes and its corresponding object.

答案1

得分: 3

你需要逐个检查每个字段,如果想逐一检查它们并记录它们是否为空。

如果要迭代所有字段,你可以使用反射,但我会质疑这种用例的适用性。

请注意,像 int age 这样的原始数据类型不能为 null,所以你不需要检查它。另外,你对 anyMatch 的使用是不正确的,因为 System.out.println 不返回布尔值。

英文:

You're going to have to check each field individually if you want to check them one-by-one and log if they are null.

You could use reflection to iterate over all fields, but I would question the applicability of such a use-case.

Note that primtives like int age cannot be null, so you wouldn't need to check for it. Plus, your usage of anyMatch is incorrect as System.out.println does not return a boolean

huangapple
  • 本文由 发表于 2020年8月5日 00:31:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63251223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定