Phương thức forEach() trong java 8

Phương thức forEach() là một tính năng mới của java 8. Nó là một phương thức mặc định (default method) được định nghĩa trong interface Iterable và Stream. Các lớp Collection extends từ interface Iterable có thể sử dụng vòng lặp forEach() để duyệt các phần tử.

Định nghĩa của phương thức forEach() trong Interface Iterable:

1. Ví dụ sử dụng forEach() với Map

package com.maixuanviet.forEach;
 
import java.util.HashMap;
import java.util.Map;
 
public class ForEachMapExample {
 
    public static void main(String[] args) {
        Map<Integer, String> hmap = new HashMap<Integer, String>();
        hmap.put(1, "Java");
        hmap.put(2, "Javascript");
        hmap.put(3, "PHP");
        hmap.put(4, "C#");
        hmap.put(5, "C++");
 
        // forEach to iterate and display each key and value pair of HashMap
        hmap.forEach((key, value) -> System.out.println(key + " - " + value));
    }
}

Output của chương trình trên như sau:

1 - Java
2 - Javascript
3 - PHP
4 - C#
5 - C++

2. Ví dụ sử dụng forEach() với List

package com.maixuanviet.forEach;
 
import java.util.Arrays;
import java.util.List;
 
public interface ForEachExample {
 
    public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java", "C#", "C++", "PHP", "Javascript");
 
        System.out.println("Iterating by passing lambda expression: ");
        languages.forEach(lang -> System.out.println(lang));
 
        System.out.println("Iterating by passing method reference: ");
        languages.forEach(System.out::println);
    }
}

Output của chương trình trên như sau:

Iterating by passing lambda expression: 
Java
C#
C++
PHP
Javascript
Iterating by passing method reference: 
Java
C#
C++
PHP
Javascript

3. Ví dụ sử dụng forEachOrdered()

Phương thức forEachOrdered() được sử dụng để duyệt các phần tử theo thứ tự được quy định bởi Stream.

package com.maixuanviet.forEach;
 
import java.util.Arrays;
import java.util.List;
 
public class ForEachOrderedExample {
 
    public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java", "C#", "C++", "PHP", "Javascript");
 
        System.out.println("Iterating by passing lambda expression: ");
        languages.stream().forEachOrdered(lang -> System.out.println(lang));
 
        System.out.println("Iterating by passing method reference: ");
        languages.stream().forEachOrdered(System.out::println);
    }
}

Output của chương trình trên như sau:

Iterating by passing lambda expression: 
Java
C#
C++
PHP
Javascript
Iterating by passing method reference: 
Java
C#
C++
PHP
Javascript

Related posts:

Java Program to Implement LinkedList API
Configure a Spring Boot Web Application
Lập trình mạng với java
An Intro to Spring Cloud Task
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Lớp Collectors trong Java 8
Java Program to Implement Repeated Squaring Algorithm
Multi Dimensional ArrayList in Java
Java Program to Implement Queue using Linked List
Java – Reader to InputStream
Spring Security Custom AuthenticationFailureHandler
Java Program to Solve the 0-1 Knapsack Problem
Java Perform to a 2D FFT Inplace Given a Complex 2D Array
Java Program to Implement Threaded Binary Tree
Java Program to Implement Kosaraju Algorithm
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Sử dụng CountDownLatch trong Java
An Intro to Spring Cloud Vault
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Hướng dẫn Java Design Pattern – Chain of Responsibility
Java Program to Implement Double Order Traversal of a Binary Tree
Giới thiệu Java 8
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Jackson – Marshall String to JsonNode
How to Find an Element in a List with Java
Intro to Inversion of Control and Dependency Injection with Spring
Hướng dẫn Java Design Pattern – Builder
JUnit5 @RunWith
Uploading MultipartFile with Spring RestTemplate
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers