如何在Java流中使用布尔条件进行过滤?

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

How to filter in java streams using boolean condition?

问题

我正在尝试使用以下布尔条件对列表进行筛选,但这不起作用。

public void write(List<? extends Student> items) {
    List<Student> list = items.stream().filter(student ->
        checkAge(student.getAge())).collect(Collectors.toList());
    super.write(list);
}

public boolean checkAge(String age) {
    if (age.length() < 5 && age.length() > 60) {
        return false;
    }

    return true;
}
英文:

I am trying to filter a list using boolean condition as below. But this does not work.

public void&#160;write(List&lt;?&#160;extends&#160;Student&gt; items) {
&#160;&#160;&#160;&#160;List&lt;Student&gt; list = items.stream().filter( student -&gt; 
          checkAge(student.getage())).collect(Collectors.toList());
    super.write(list);
 }

&#160;public boolean&#160;checkAge(String&#160;age) {
&#160;&#160;&#160;&#160;if&#160;(age.length() &lt; 5&#160;&amp;&amp; age.length() &gt; 60) {
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;return&#160;false;
&#160;&#160;&#160;&#160;}

&#160;&#160;&#160;&#160;return&#160;true;
&#160;}

答案1

得分: 1

一个数量不能同时小于5和大于60。因此,以下代码没有意义:

if (age.length() < 5 && age.length() > 60) {
    return false;
}

您希望将其更改为类似以下的形式:

if (age.length() < 5 || age.length() > 60) {
    return false;
}
英文:

A quantity can never be less than 5 and greater than 60 at the same time. So, the following code doesn't make sense:

if (age.length() &lt; 5 &amp;&amp; age.length() &gt; 60) {
	return false;
}

You would like to change it to something like:

if (age.length() &lt; 5 || age.length() &gt; 60) {
	return false;
}

huangapple
  • 本文由 发表于 2020年10月20日 23:26:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64448372.html
匿名

发表评论

匿名网友

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

确定