import java.util.Arrays;
import java.util.*;
import java.util.stream.Collectors;
// double the first even number greater than 3
public class FirstDouble {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,5,6,7,8,9);
/* int result = 0;
for(int e : numbers)
{
if(e>3 && e%2==0)
{
result = e*2;
break;
}
}
System.out.println(result);
*/
System.out.println(
numbers.stream()
.filter(Sample::isGT3)
.filter(Sample::isEven)
.map(Sample::doubleIt)
.findFirst());
}
public boolean isGt3(int number) {
return number > 3;
}
public boolean isEven(int number) {
return number % 2 == 0;
}
public int doubleIt(int number) {
return number * 2;
}
}
答案 0 :(得分:1)
需要进行三次修改才能编译代码:
Sample
重命名为FirstDouble
,以便正确引用该课程isGt3
重命名为isGT3
static
修饰符添加到isGT3
,isEven
和doubleIt
之后,它打印出Optional[12]
。如果只打印该号码,请在get
之后添加findFirst
。