Java forEach() 使用示例

x33g5p2x  于2022-09-24 转载在 Java  
字(8.9k)|赞(0)|评价(0)|浏览(254)

Java forEach 方法迭代源的元素并执行给定的操作。在 Java 8 中,Iterable 接口引入了 forEach 作为默认方法,将动作作为 Consumer 接受,而 Map 接口还引入了 forEach 作为默认方法,将 BiConsumer 作为动作接受。在 Java 8 中,Stream 还具有 forEach 方法,该方法接受 Consumer 作为操作。 Iterable 接口由 Collection 扩展,因此 forEach 方法可用于 ListSetQueue 等。
在本文中,我们将通过示例详细提供使用 forEach 方法。

1. Iterable 中的 forEach()

java.lang.Iterable 接口在 Java 8 中引入了 forEach 默认方法,如下所示。

default void forEach(Consumer<? super T> action)

action:对每个元素执行的动作为 Consumer

上面的 forEach 方法对 Iterable 的每个元素执行给定的操作。 forEach 将在所有元素都已处理或操作引发异常时停止。 forEach 按迭代顺序执行动作。
如果 action 修改了元素的来源,则 forEach 的行为是未指定的,除非覆盖类已指定并发修改策略。

Iterable 通过以下接口进行扩展。
(a) java.util.Collection:我们可以将 forEach 方法与 ListSetQueue 等一起使用。
(b) java.nio.file.DirectoryStream:我们可以将 forEach 方法与 DirectoryStream 一起使用,DirectoryStream 是一个迭代目录中条目的对象。要实例化 DirectoryStream,请使用 Files.newDirectoryStream() 方法。
(c) java.nio.file.Path:我们可以将 forEach 方法与 Path 一起使用,Path 是一个用于在文件系统中定位文件的对象。要实例化 Path,请使用 Paths.get() 方法。

2. Map中的 forEach()

java.util.Map 接口在 Java 8 中引入了 forEach 默认方法,如下所示。

default void forEach(BiConsumer<? super K,? super V> action)

action:为每个条目执行的动作为 BiConsumer

上面的 forEach 方法对 Map 的每个条目执行给定的操作。 forEach 将在所有条目都已处理或操作引发异常时停止。 forEach 按照条目集迭代的顺序执行操作。
我们可以对 Map 的所有实现类使用 forEach 方法,例如 HashMapLinkedHashMapTreeMapConcurrentHashMap 等。

3. Stream中的 forEach()

a.forEach 来自 java.util.stream.Stream

void forEach(Consumer<? super T> action)

对该 Stream 的每个元素执行给定的操作作为 Consumer
b.forEach 来自 java.util.stream.IntStream

void forEach(IntConsumer action)

对该 IntStream 的每个元素执行给定的操作作为 IntConsumer
c.forEach 来自 java.util.stream.LongStream

void forEach(LongConsumer action)

对该 LongStream 的每个元素执行给定的操作作为 LongConsumer
d.forEach 来自 java.util.stream.DoubleStream

void forEach(DoubleConsumer action)

对此 DoubleStream 的每个元素执行给定的操作作为 DoubleConsumer

4. List中的forEach()

要使用 List.forEach 方法,我们需要将 Consumer 作为操作传递。我们可以将 Consumer 作为 lambda 表达式或方法引用传递。
使用 lambda 表达式查找代码片段。

List<String> techList = Arrays.asList("Java", "Spring", "Oracle");
techList.forEach(s -> System.out.println(s));

找到带有方法参考的代码片段。

techList.forEach(System.out::println);

找到输出。

Java
Spring
Oracle

使用 List 查找 forEach 方法的另一个示例。这里我们有一个对象列表。
ForEachDemoWithList.java

package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class ForEachDemoWithList {
  public static void main(String[] args) {
	List<Student> list = new ArrayList<>();
	list.add(new Student("Ram", "male"));
	list.add(new Student("Meera", "female"));
	list.add(new Student("Kabir", "male"));

	System.out.println("---Using lambda expression---");
	Consumer<Student> maleStds = (Student s) -> {
	  if ("male".equals(s.getGender())) {
		System.out.print(s.getName() + " ");
	  }
	};

	list.forEach(maleStds);

	System.out.println("\n---Using method reference---");
	list.forEach(Student::printMaleStds);
  }
}
class Student {
  private String name;
  private String gender;
  public Student(String name, String gender) {
	this.name = name;
	this.gender = gender;
  }
  public void printMaleStds() {
	if ("male".equals(getGender())) {
	  System.out.print(getName() +" ");
	}
  }
  //Sets and Gets
}

输出

---Using lambda expression---
Ram Kabir 
---Using method reference---
Ram Kabir

5. Set中的forEach()

要使用 Set.forEach 方法,我们需要将 Consumer 作为 lambda 表达式或方法引用传递。
创建一个 Set

Set<Integer> set = new HashSet<>();
set.add(15); 
set.add(10);
set.add(20);

使用 forEach 和 lambda 表达式来打印数据。

set.forEach(s -> System.out.println(s));

使用方法参考。

set.forEach(System.out::println);

再找到一个使用 forEachSet 的示例。
ForEachDemoWithSet.java

package com.concretepage;
import java.util.HashSet;
import java.util.Set;
public class ForEachDemoWithSet {
  public static void main(String[] args) {
	Set<Book> books = new HashSet<>();
	books.add(new Book("Book A", 60));
	books.add(new Book("Book B", 30));
	books.add(new Book("Book C", 40));

	// With lambda expression
	books.forEach(b -> {
	  if (b.getPrice() < 50) {
		System.out.println(b.getName());
	  }
	}); //Output: Book B, Book C
	
	// With method reference
	books.forEach(Book::printBook); //Output: Book B, Book C
  }
}
class Book {
  private String name;
  private int price;
  public Book(String name, int price) {
	this.name = name;
	this.price = price;
  }
  public void printBook() {
	if (price < 50) {
	  System.out.println(name);
	}
  }
  //Sets, Gets, equals, hashCode
}

6. Queue中的forEach()

要使用 Queue.forEach 方法,我们需要将 Consumer 作为 lambda 表达式或方法引用传递。
Queue 找到 forEach 的例子。我们在这里用它的实现类 ArrayDeque 实例化 Queue
ForEachDemoWithQueue.java

package com.concretepage;
import java.util.ArrayDeque;
public class ForEachDemoWithQueue {
  public static void main(String[] args) {
	ArrayDeque<String> queue = new ArrayDeque<String>();
	queue.add("BB");
	queue.add("CC");

	queue.offerFirst("AA");
	queue.offerLast("DD");

	// With lambda expression
	queue.forEach(e -> System.out.println(e)); //AA, BB, CC, DD

	// With method reference
	queue.forEach(System.out::println); //AA, BB, CC, DD
  }
}

7. DirectoryStream中的forEach()

要使用 DirectoryStream.forEach 方法,我们需要将 Consumer 作为 lambda 表达式或方法引用传递。
使用 lambda 表达式查找 forEachDirectoryStream 的示例。
WithDirectoryStream.java

package com.concretepage;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WithDirectoryStream {
  public static void main(String[] args) throws IOException {
	  Path dir = Paths.get("C:/page");
	  DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir, "*.{txt,jpg}");

	  dirStream.forEach(f -> System.out.println(f.getFileName()));
  }
}

8. Path中的forEach()

要使用 Path.forEach 方法,我们需要将 Consumer 作为 lambda 表达式或方法引用传递。
使用 lambda 表达式查找 forEachPath 的示例。
ForEachDemoWithPath.java

package com.concretepage;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ForEachDemoWithPath {
  public static void main(String[] args) {
	  Path dir = Paths.get("C:/page/java/java8/myclass.java");
	  dir.forEach(f -> System.out.println(f.getFileName()));
  }
}

9. Map中的forEach()

要使用 Map.forEach 方法,我们需要将 BiConsumer 作为 lambda 表达式或方法引用传递。
假设我们有以下 Map

Map<Integer, String> map = new HashMap<>();
map.put(101, "Java");
map.put(102, "Angular");
map.put(103, "Spring");

找到 forEach 以迭代 Map

map.forEach((k, v) -> System.out.println(k + "-" + v));

我们将得到以下输出。

101-Java
102-Angular
103-Spring

Map 再找到一个 forEach 的例子。
ForEachDemoWithMap.java

package com.concretepage;
import java.util.HashMap;
import java.util.Map;
public class ForEachDemoWithMap {
  public static void main(String[] args) {
	Map<Integer, User> map = new HashMap<>();
	map.put(101, new User("Mahesh", true));
	map.put(102, new User("Suresh", false));
	map.put(103, new User("Krishn", true));

	System.out.println("---Passing BiConsumer as lambda expression---");
	map.forEach((k, v) -> {
	  if (v.isActive() == true) {
		System.out.println(k + " - " + v.getUserName());
	  }
	});

	System.out.println("---Passing BiConsumer as method reference---");
	map.forEach(User::printActiveUser);
  }
}
class User {
  private String userName;
  private boolean active;

  public User(String userName, boolean active) {
	this.userName = userName;
	this.active = active;
  }
  public static void printActiveUser(int id, User user) {
	if (user.isActive() == true) {
	  System.out.println(id + " - " + user.getUserName());
	}
  }
  //Sets and Gets
}

输出

---Passing BiConsumer as lambda expression---
101 - Mahesh
103 - Krishn
---Passing BiConsumer as method reference---
101 - Mahesh
103 - Krishn

10. Stream中的forEach()

要使用 Stream.forEach 方法,我们需要将 Consumer 作为 lambda 表达式或方法引用传递。找到例子。
ForEachDemoWithStream1.java

package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ForEachDemoWithStream1 {
  public static void main(String[] args) {
	Stream<String> stream = Stream.of("Mahesh", "Nilesh", "Mohit");
	stream.forEach(e -> System.out.println(e)); //Mahesh, Nilesh, Mohit

	List<String> list = Arrays.asList("Mahesh", "Nilesh", "Mohit");
	list.stream().filter(e -> e.startsWith("M")).forEach(e -> System.out.println(e)); //Mahesh, Mohit
	
	list.stream().filter(e -> e.startsWith("M")).forEach(System.out::println); //Mahesh, Mohit
	
	list.stream().sorted().forEach(e -> System.out.println(e)); //Mahesh, Mohit, Nilesh
  }
}

forEach 方法与 IntStream 传递 IntConsumerLongStream 传递 LongConsumerDoubleStream 传递 DoubleConsumer 作为操作一起使用。
找到示例。
ForEachDemoWithStream2.java

package com.concretepage;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class ForEachDemoWithStream2 {
  public static void main(String[] args) {
    // With IntStream
    IntStream.of(30, 40, 50).forEach(s -> System.out.println(s)); //30, 40, 50
    IntStream.of(30, 40, 50).forEach(System.out::println); //30, 40, 50
	
    IntStream.of(30, 40, 50).flatMap(e -> IntStream.of(e / 10))
	    .forEach(e -> System.out.println(e)); //3, 4, 5

    // With LongStream	
    LongStream.of(300, 400, 500).forEach(s -> System.out.println(s)); //300, 400, 500
    LongStream.of(300, 400, 500).forEach(System.out::println); //300, 400, 500
	
    LongStream.of(300, 400, 500).flatMap(e -> LongStream.of(e / 100))
	    .forEach(e -> System.out.println(e)); //3, 4, 5
	
    // With DoubleStream
    DoubleStream.of(30.15, 40.35, 50.55).forEach(s -> System.out.println(s)); //30.15, 40.35, 50.55
    DoubleStream.of(30.15, 40.35, 50.55).forEach(System.out::println); //30.15, 40.35, 50.55
	
    DoubleStream.of(30.15, 40.35, 50.55).flatMap(e -> DoubleStream.of(e * 10))
	    .forEach(e -> System.out.println(e)); //301.5, 403.5, 505.5    
  }
}

相关文章