Looping List with forEach
Below
example will show the demonstration of how to use forEach with List
General way to loop a
List:
-----------------------------------------------------------------------------------------
Code:
---------------------------
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String>
items = new ArrayList<>();
items.add("Zero");
items.add("One");
items.add("Two");
items.add("Three");
items.add("four");
items.add("five");
for(String item : items){
System.out.println(item);
}
}
}
Output:
-----------------------
Zero
One
Two
Three
four
five
Using forEach:
-----------------------------------------------------------------------------------------
1. Looping
List with forEach, Actually in Java 8, we can use lambda expression
-----------------------------------------------------------------------------------------
Code:
-----------------------------------
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String>
items = new ArrayList<>();
items.add("Zero");
items.add("One");
items.add("Two");
items.add("Three");
items.add("four");
items.add("five");
// displaying
result by using lambda and forEach
items.forEach(item -> System.out.println(item));
}
}
Output:
-----------------------
Zero
One
Two
Three
four
five
-----------------------------------------------------------------------------------------
2. Looping
List with forEach, Actually in Java 8, we can use method reference
-----------------------------------------------------------------------------------------
Code:
-----------------------------
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String>
items = new ArrayList<>();
items.add("Zero");
items.add("One");
items.add("Two");
items.add("Three");
items.add("four");
items.add("five");
// looping by using
method reference
items.forEach(System.out::println);
}
}
Output:
----------------------
Zero
One
Two
Three
four
five
One
Two
Three
four
five
-----------------------------------------------------------------------------------------
3. Looping
List with forEach, Actually in Java 8, we can use stream and filter
-----------------------------------------------------------------------------------------
Code:
--------------------------
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String>
items = new ArrayList<>();
items.add("Zero");
items.add("One");
items.add("Two");
items.add("Three");
items.add("four");
items.add("five");
// looping List by
using Stream and filter
items.stream().filter(s -> s.contains("B")).forEach(System.out::println);
}
}
Output:
-------------------
One
No comments:
Post a Comment