Lamda Expression
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class forEach {
public static void main(String[] args) {
List<String> alist = Arrays.asList("TX", "NY", "CA");// ArrayList
// 1. for loop
System.out.println("-------Using For Loop--------");
for (int i = 0; i < alist.size(); i++) {
System.out.println(alist.get(i));
}
// 2. for loop another way
System.out.println("-------Using For Loop with semicolon--------");
for (String x : alist) {
System.out.println(x);
}
// 3. with anonymous class
System.out.println("-------Anonymous class--------");
alist.forEach(new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
// System.out.println("The names is : " + str);
}
});
// 4. above block of code can also be written as below
System.out.println("-------Delta expression--------");
alist.forEach(str -> System.out.println(str));
// 5. above blocks of code can also be written as below
System.out.println("-------Method References--------");
alist.forEach(System.out::println);
// with number list
List<Integer> blist = Arrays.asList(1, 5, 6, 3);// Integer Array List
System.out.println("-------with integer arraylist--------");
blist.forEach(x -> System.out.println(x));
System.out.println("---------------------------");
blist.forEach(System.out::println);
}
}
Output:
-------Using For Loop--------
TX
NY
CA
-------Using For Loop with semicolon--------
TX
NY
CA
-------Anonymous class--------
TX
NY
CA
-------Delta expression--------
TX
NY
CA
-------Method References--------
TX
NY
CA
-------with integer arraylist--------
1
5
6
3
---------------------------
1
5
6
3
No comments:
Post a Comment