英文:
How to return first non empty string value from list of strings(sorted) in java
问题
我有一组字符串值,想要返回第一个非空值,而且这个列表是有序的。怎么做?
for (String data : schoolDetails.getStudentdata()) {
    // 需要获取第一个非空数据
}
任何线索将会很有帮助。提前致谢。
英文:
I have list of string values and wants to return first non empty value and this list is sorted. how to achieve this?
for( String data:schoolDetails.getStudentdata(){
 // have to get first non empty data 
}
any leads would be helpful.Thanks in advance.
答案1
得分: 2
使用 Java 8 引入的 Streams,我们可以以函数式的方式表达这个逻辑:
return schoolDetails.getStudentdata().stream()
    .filter(Objects::nonNull)
    .findFirst()
    .orElse(null);
由于不能保证存在非 null 的值,如果不存在非 null 的值,我们将返回 null。或者,我们可以跳过 orElse(...) 步骤,返回一个 Optional<String>,表示结果可能为空:
return schoolDetails.getStudentdata().stream()
    .filter(Objects::nonNull)
    .findFirst();
此外,我们还可以修改过滤条件,例如,除了 Objects::nonNull,还可以使用 String::isBlank 并结合 Predicate::not:
return schoolDetails.getStudentdata().stream()
    .filter(Objects::nonNull)
    .filter(Predicate.not(String::isBlank))
    .findFirst();
英文:
With the introduction of Streams in Java 8, we can express this in a functional way:
return schoolDetails.getStudentdata().stream()
    .filter(Objects::nonNull)
    .findFirst()
    .orElse(null);
Since it is not guaranteed that a non-null value exists, we return null if no non-null value exists. Alternatively, we can skip the orElse(...)-step and return an Optional<String>, signaling that the result might be empty:
return schoolDetails.getStudentdata().stream()
    .filter(Objects::nonNull)
    .findFirst();
We can furthermore modify what we want to filter by, for example, using String::isBlank in addition to Objects::nonNull and the help of Predicate::not:
return schoolDetails.getStudentdata().stream()
    .filter(Objects::nonNull)
    .filter(Predicate.not(String::isBlank))
    .findFirst();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论