Java 8 forEach方法指南

x33g5p2x  于4个月前 转载在 Java  
字(5.6k)|赞(0)|评价(0)|浏览(158)

Java 8教程

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

1.List的forEach()方法

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

public static void forEachWithList() {

    final List < Person > items = new ArrayList < > ();
    items.add(new Person(100, "Ramesh"));
    items.add(new Person(100, "A"));
    items.add(new Person(100, "B"));
    items.add(new Person(100, "C"));
    items.add(new Person(100, "D"));

    for (final Person item: items) {
        System.out.println(item.getName());
    }
}

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

public static void forEachWithList() {

    final List < Person > items = new ArrayList < > ();
    items.add(new Person(100, "Ramesh"));
    items.add(new Person(100, "A"));
    items.add(new Person(100, "B"));
    items.add(new Person(100, "C"));
    items.add(new Person(100, "D"));

    //lambda
    items.forEach(item - > System.out.println(item.getName()));

    //Output : C
    items.forEach(item - > {
        if ("C".equals(item)) {
            System.out.println(item);
        }
    });

    //method reference
    //Output : A,B,C,D,E
    items.forEach(System.out::println);

    //Stream and filter
    //Output : B
    items.stream()
        .filter(s - > s.getName().equals("Ramesh"))
        .forEach(System.out::println);
}

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

2.Map的forEach()方法

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

public static void forEachWithMap() {

    // Before Java 8, how to loop map
    final Map < Integer, Person > map = new HashMap < > ();
    map.put(1, new Person(100, "Ramesh"));
    map.put(2, new Person(100, "Ram"));
    map.put(3, new Person(100, "Prakash"));
    map.put(4, new Person(100, "Amir"));
    map.put(5, new Person(100, "Sharuk"));

    for (final Entry < Integer, Person > entry: map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue().getName());
    }
}

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

public static void forEachWithMap() {

    // Before Java 8, how to loop map
    final Map < Integer, Person > map = new HashMap < > ();
    map.put(1, new Person(100, "Ramesh"));
    map.put(2, new Person(100, "Ram"));
    map.put(3, new Person(100, "Prakash"));
    map.put(4, new Person(100, "Amir"));
    map.put(5, new Person(100, "Sharuk"));

    //  In Java 8, you can loop a Map with forEach + lambda expression.
    map.forEach((k, p) - > {
        System.out.println(k);
        System.out.println(p.getName());
    });
}

3.Set的forEach()方法

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

public static void forEachWithSet() {

    final Set < String > items = new HashSet < > ();
    items.add("A");
    items.add("B");
    items.add("C");
    items.add("D");
    items.add("E");

    // before java 8
    for (final String item: items) {
        System.out.println(item);
    }

    // java 8 with lambda expression
    //Output : A,B,C,D,E
    items.forEach(item - > System.out.println(item));

    //Output : C
    items.forEach(item - > {
        if ("C".equals(item)) {
            System.out.println(item);
        }
    });

    //method reference
    items.forEach(System.out::println);

    //Stream and filter
    items.stream()
        .filter(s - > s.contains("B"))
        .forEach(System.out::println);

}

真实示例

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

package com.ramesh.corejava.devguide.java8;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ForEachRealTimeExamples {

    public static void main(String[] args) {
        List < Entity > entities = getEntities();

        List < EntityDTO > dtos = new ArrayList < > ();
        entities.forEach(entity - > {
            dtos.add(new EntityDTO(entity.getId(), entity.getEntityName()));
        });

        dtos.forEach(e - > {
            System.out.println(e.getId());
            System.out.println(e.getEntityName());
        });

    }

    public static List < Entity > getEntities() {
        List < Entity > entities = new ArrayList < > ();
        entities.add(new Entity(100, "entity 1"));
        entities.add(new Entity(100, "entity 2"));
        entities.add(new Entity(100, "entity 3"));
        return entities;
    }
}

class EntityDTO {
    private int id;
    private String entityName;
    private Date createdAt;
    private String createBy;
    private Date updatedAt;
    private String updatedBy;

    public EntityDTO(int id, String entityName) {
        this.id = id;
        this.entityName = entityName;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getEntityName() {
        return entityName;
    }
    public void setEntityName(String entityName) {
        this.entityName = entityName;
    }
    public Date getCreatedAt() {
        return createdAt;
    }
    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }
    public String getCreateBy() {
        return createBy;
    }
    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }
    public Date getUpdatedAt() {
        return updatedAt;
    }
    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }
    public String getUpdatedBy() {
        return updatedBy;
    }
    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }
}

class Entity {
    private int id;
    private String entityName;
    private Date createdAt;
    private String createBy;
    private Date updatedAt;
    private String updatedBy;

    public Entity(int id, String entityName) {
        super();
        this.id = id;
        this.entityName = entityName;
        this.createdAt = new Date();
        this.createBy = "ramesh";
        this.updatedAt = new Date();
        this.updatedBy = "ramesh";
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getEntityName() {
        return entityName;
    }
    public void setEntityName(String entityName) {
        this.entityName = entityName;
    }
    public Date getCreatedAt() {
        return createdAt;
    }
    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }
    public String getCreateBy() {
        return createBy;
    }
    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }
    public Date getUpdatedAt() {
        return updatedAt;
    }
    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }
    public String getUpdatedBy() {
        return updatedBy;
    }
    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }
}

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

相关文章

微信公众号

最新文章

更多