Java 8 forEach方法指南

x33g5p2x  于2022-10-15 转载在 Java  
字(5.6k)|赞(0)|评价(0)|浏览(1664)

Java 8教程

Java8 forEach()提供了一种新的方法来迭代元素。它在Iterable和Stream接口中定义。
它是Iterable接口中定义的默认方法。扩展Iterable接口的集合类可以使用forEach()循环来迭代元素。
在本文中,我们将学习如何forEach()方法迭代集合、Map和流。

1.List的forEach()方法

让我们使用normal forEach来循环List。

  1. public static void forEachWithList() {
  2. final List < Person > items = new ArrayList < > ();
  3. items.add(new Person(100, "Ramesh"));
  4. items.add(new Person(100, "A"));
  5. items.add(new Person(100, "B"));
  6. items.add(new Person(100, "C"));
  7. items.add(new Person(100, "D"));
  8. for (final Person item: items) {
  9. System.out.println(item.getName());
  10. }
  11. }

在Java8中,可以使用forEach+lambda表达式或方法引用循环List。

  1. public static void forEachWithList() {
  2. final List < Person > items = new ArrayList < > ();
  3. items.add(new Person(100, "Ramesh"));
  4. items.add(new Person(100, "A"));
  5. items.add(new Person(100, "B"));
  6. items.add(new Person(100, "C"));
  7. items.add(new Person(100, "D"));
  8. //lambda
  9. items.forEach(item - > System.out.println(item.getName()));
  10. //Output : C
  11. items.forEach(item - > {
  12. if ("C".equals(item)) {
  13. System.out.println(item);
  14. }
  15. });
  16. //method reference
  17. //Output : A,B,C,D,E
  18. items.forEach(System.out::println);
  19. //Stream and filter
  20. //Output : B
  21. items.stream()
  22. .filter(s - > s.getName().equals("Ramesh"))
  23. .forEach(System.out::println);
  24. }

请参阅上面示例中的注解是自描述性的。

2.Map的forEach()方法

首先,让我们看看使用forEach循环Map的正常方式。

  1. public static void forEachWithMap() {
  2. // Before Java 8, how to loop map
  3. final Map < Integer, Person > map = new HashMap < > ();
  4. map.put(1, new Person(100, "Ramesh"));
  5. map.put(2, new Person(100, "Ram"));
  6. map.put(3, new Person(100, "Prakash"));
  7. map.put(4, new Person(100, "Amir"));
  8. map.put(5, new Person(100, "Sharuk"));
  9. for (final Entry < Integer, Person > entry: map.entrySet()) {
  10. System.out.println(entry.getKey());
  11. System.out.println(entry.getValue().getName());
  12. }
  13. }

在Java8中,可以使用forEach和lambda表达式循环Map。

  1. public static void forEachWithMap() {
  2. // Before Java 8, how to loop map
  3. final Map < Integer, Person > map = new HashMap < > ();
  4. map.put(1, new Person(100, "Ramesh"));
  5. map.put(2, new Person(100, "Ram"));
  6. map.put(3, new Person(100, "Prakash"));
  7. map.put(4, new Person(100, "Amir"));
  8. map.put(5, new Person(100, "Sharuk"));
  9. // In Java 8, you can loop a Map with forEach + lambda expression.
  10. map.forEach((k, p) - > {
  11. System.out.println(k);
  12. System.out.println(p.getName());
  13. });
  14. }

3.Set的forEach()方法

下面的示例演示如何将forEach方法与集合、流等一起使用。

  1. public static void forEachWithSet() {
  2. final Set < String > items = new HashSet < > ();
  3. items.add("A");
  4. items.add("B");
  5. items.add("C");
  6. items.add("D");
  7. items.add("E");
  8. // before java 8
  9. for (final String item: items) {
  10. System.out.println(item);
  11. }
  12. // java 8 with lambda expression
  13. //Output : A,B,C,D,E
  14. items.forEach(item - > System.out.println(item));
  15. //Output : C
  16. items.forEach(item - > {
  17. if ("C".equals(item)) {
  18. System.out.println(item);
  19. }
  20. });
  21. //method reference
  22. items.forEach(System.out::println);
  23. //Stream and filter
  24. items.stream()
  25. .filter(s - > s.contains("B"))
  26. .forEach(System.out::println);
  27. }

真实示例

在实际项目中,我们可以使用forEach()方法循环Java类进行转换。
让我们创建Entity类和EntityDTO类,循环遍历实体列表,并使用forEach()方法将Entity转换为EntityDTO。
让我们演示Java 8 forEach()方法在实际项目中的用法:

  1. package com.ramesh.corejava.devguide.java8;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.List;
  5. public class ForEachRealTimeExamples {
  6. public static void main(String[] args) {
  7. List < Entity > entities = getEntities();
  8. List < EntityDTO > dtos = new ArrayList < > ();
  9. entities.forEach(entity - > {
  10. dtos.add(new EntityDTO(entity.getId(), entity.getEntityName()));
  11. });
  12. dtos.forEach(e - > {
  13. System.out.println(e.getId());
  14. System.out.println(e.getEntityName());
  15. });
  16. }
  17. public static List < Entity > getEntities() {
  18. List < Entity > entities = new ArrayList < > ();
  19. entities.add(new Entity(100, "entity 1"));
  20. entities.add(new Entity(100, "entity 2"));
  21. entities.add(new Entity(100, "entity 3"));
  22. return entities;
  23. }
  24. }
  25. class EntityDTO {
  26. private int id;
  27. private String entityName;
  28. private Date createdAt;
  29. private String createBy;
  30. private Date updatedAt;
  31. private String updatedBy;
  32. public EntityDTO(int id, String entityName) {
  33. this.id = id;
  34. this.entityName = entityName;
  35. }
  36. public int getId() {
  37. return id;
  38. }
  39. public void setId(int id) {
  40. this.id = id;
  41. }
  42. public String getEntityName() {
  43. return entityName;
  44. }
  45. public void setEntityName(String entityName) {
  46. this.entityName = entityName;
  47. }
  48. public Date getCreatedAt() {
  49. return createdAt;
  50. }
  51. public void setCreatedAt(Date createdAt) {
  52. this.createdAt = createdAt;
  53. }
  54. public String getCreateBy() {
  55. return createBy;
  56. }
  57. public void setCreateBy(String createBy) {
  58. this.createBy = createBy;
  59. }
  60. public Date getUpdatedAt() {
  61. return updatedAt;
  62. }
  63. public void setUpdatedAt(Date updatedAt) {
  64. this.updatedAt = updatedAt;
  65. }
  66. public String getUpdatedBy() {
  67. return updatedBy;
  68. }
  69. public void setUpdatedBy(String updatedBy) {
  70. this.updatedBy = updatedBy;
  71. }
  72. }
  73. class Entity {
  74. private int id;
  75. private String entityName;
  76. private Date createdAt;
  77. private String createBy;
  78. private Date updatedAt;
  79. private String updatedBy;
  80. public Entity(int id, String entityName) {
  81. super();
  82. this.id = id;
  83. this.entityName = entityName;
  84. this.createdAt = new Date();
  85. this.createBy = "ramesh";
  86. this.updatedAt = new Date();
  87. this.updatedBy = "ramesh";
  88. }
  89. public int getId() {
  90. return id;
  91. }
  92. public void setId(int id) {
  93. this.id = id;
  94. }
  95. public String getEntityName() {
  96. return entityName;
  97. }
  98. public void setEntityName(String entityName) {
  99. this.entityName = entityName;
  100. }
  101. public Date getCreatedAt() {
  102. return createdAt;
  103. }
  104. public void setCreatedAt(Date createdAt) {
  105. this.createdAt = createdAt;
  106. }
  107. public String getCreateBy() {
  108. return createBy;
  109. }
  110. public void setCreateBy(String createBy) {
  111. this.createBy = createBy;
  112. }
  113. public Date getUpdatedAt() {
  114. return updatedAt;
  115. }
  116. public void setUpdatedAt(Date updatedAt) {
  117. this.updatedAt = updatedAt;
  118. }
  119. public String getUpdatedBy() {
  120. return updatedBy;
  121. }
  122. public void setUpdatedBy(String updatedBy) {
  123. this.updatedBy = updatedBy;
  124. }
  125. }

这篇文章的源代码可以在GitHub Repository上找到。

相关文章

最新文章

更多