When using the for statement, I wondered what would happen if I wrote it with a lambda expression, so I will put it as a memorandum.
The behavior in the for statement
For statement test 1
public static void main(String[] args){
int[] foos = {1, 2, 3, 4, 5};
//Ordinary For statement
for(int i = 0; i < foos.length; i++){
function(foos[i]);
}
//Extended For statement
for(int foo : foos){
function(foo);
}
//lambda expression
Arrays.stream(foos).forEach(foo -> function(foo));
//With lambda expression type inference * Test.function(int)Is calling
Arrays.stream(foos).forEach(Test::function);
}
For statement test 2
public static void main(String[] args){
int[] foos = {1, 2, 3, 4, 5};
//Ordinary For statement
for(int i = 0; i < foos.length; i++){
if(condition(foos[i])){
function(foos[i]);
}
}
//Extended For statement
for(int foo : foos){
if(condition(foo)){
function(foo);
}
}
//lambda expression naive way of writing
Arrays.stream(foos).forEach(foo -> {
if(condition(foo)){
function(foo);
}
});
//lambda expression more functional
Arrays.stream(foos)
.filter(foo -> condition(foo))
.forEach(foo -> function(foo));
//With lambda expression type inference
Arrays.stream(foos)
.filter(Test::condition)
.forEach(Test::function);
}
For statement test 3
//Ordinary For statement
for(int i = 0; i < foos.length; i++){
int tmp = offset(foos[i]);
function(tmp);
}
//Extended For statement
for(int foo : foos){
int tmp = offset(foo);
function(tmp);
}
//lambda expression
Arrays.stream(foos)
.map(Test::offset)
.forEach(Test::function);
Recommended Posts