Java forEach 方法示例

x33g5p2x  于11个月前 转载在 Java  
字(3.0k)|赞(0)|评价(0)|浏览(94)

Java forEach 方法是一种实用方法,可用于迭代 Java 集合或流。在使用 Stream 或任何 Java 集合(如 ListMap、​​SetStackQueue 等)时,它非常方便.

在本文中,您将找到带有 List、Map 和 Stream 的 Java forEach 方法示例。

Java forEach 方法

Java forEach 方法在 Iterable 接口中定义。由于 Collection 接口扩展了 Iterable 接口,因此该方法可用于所有 Java 集合类。

forEach() 方法将 Consumer 作为参数,并为集合中的每个项目执行由消费者定义的操作。

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Consumer 是一个函数式接口。它可以使用 Java 的匿名类语法或使用 Lambda 表达式创建:

// Creating a consumer using the anonymous class syntax
Consumer<String> action = new Consumer<String>() {
    @Override
    public void accept(String s) {

        // perform action
        System.out.println(s);
    }
};

// Creating a Consumer using a lambda expression
Consumer<String> action = s -> {
    // perform action
    System.out.println(s);
};

// The curly braces can be omitted if the lambda expression's body consists of a single line
Consumer<String> action = s -> System.out.println(s);

现在让我们看看带有 List、Map 和 Stream 的 forEach 方法的示例。

每个示例的 Java 列表

import java.util.Arrays;
import java.util.List;

public class ListForEachExample {
    public static void main(String[] args) {

        List<String> names = Arrays.asList("John", "Jack", "Sachin", "Mark");

        // List forEach with lambda expression
        names.forEach(name -> {
            System.out.printf("Hello %s%n", name);
        });

        // List forEach with Method reference
        names.forEach(System.out::println);

    }
}
# Output
Hello John
Hello Jack
Hello Sachin
Hello Mark
John
Jack
Sachin
Mark

Java Map forEach 示例

import java.util.HashMap;
import java.util.Map;

public class MapForEachExample {
    public static void main(String[] args) {

        Map<Integer, String> employeeIdNameMapping = new HashMap<>();

        employeeIdNameMapping.put(101, "Jack");
        employeeIdNameMapping.put(102, "Maria");
        employeeIdNameMapping.put(103, "Robert");
        employeeIdNameMapping.put(104, "Joseph");

        // Map forEach example
        employeeIdNameMapping.forEach((id, name) -> {
            System.out.printf("Employee ID: %s, Name: %s%n", id, name);
        });

    }
}
# Output
Employee ID: 101, Name: Jack
Employee ID: 102, Name: Maria
Employee ID: 103, Name: Robert
Employee ID: 104, Name: Joseph

Java Stream forEach 示例

Java Stream forEach 方法与 Java Collections forEach 方法不同。它在 Stream 接口中定义。但是,Stream forEach 方法也接受 Consumer。所以它的工作方式与 Collections forEach 方法相同。让我们看一个例子:

import java.util.stream.Stream;

public class StreamForEachExample {
    public static void main(String[] args) {

        Stream<String> countries = Stream.of("India", "China", "United States", "United Kingdom", "Germany", "France");

        // Stream forEach with lambda expression
        countries.forEach(name -> {
            System.out.printf("Hello %s%n", name);
        });



        Stream<String> programmingLanguages = Stream.of("Java", "Go", "Rust", "C++", "Swift");

        // Stream forEach with Method reference
        programmingLanguages.forEach(System.out::println);



        Stream<Integer> numbers = Stream.of(2, 5, 7, 8, 10, 23, 44, 68);

        // Stream forEach with filter
        numbers.filter(num -> num % 2 == 0)
                .forEach(num -> System.out.println(num));
    }
}
# Output
Hello India
Hello China
Hello United States
Hello United Kingdom
Hello Germany
Hello France
Java
Go
Rust
C++
Swift
2
8
10
44
68

相关文章

热门文章

更多