java8 list和map的forEach

list forEach示例

public class HelloWorld {
    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        for(int i=1;i<=10;i++) {
            list.add(new User(i, "user_" + i));
        }
        //list forEach
        list.forEach(user -> {
            user.setId(user.getId() + 10);
            System.out.println(user);
        });

    }
    private static class User{
        public User(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        Integer id;
        String name;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

}

执行结果:

User{id=11, name='user_1'}
User{id=12, name='user_2'}
User{id=13, name='user_3'}
User{id=14, name='user_4'}
User{id=15, name='user_5'}
User{id=16, name='user_6'}
User{id=17, name='user_7'}
User{id=18, name='user_8'}
User{id=19, name='user_9'}
User{id=20, name='user_10'}

 

Map的forEach

public class HelloWorld {
    public static void main(String[] args) {
        Map<Integer, User> map = new HashMap<>(10);
        for(int i=1;i<=10;i++) {
            map.put(i, new User(i, "user_" + i));
        }
        //map forEach
        map.forEach((k, v) -> {
            System.out.println("key: " + k + ", value:" + v);
        });

    }
    private static class User{
        public User(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        Integer id;
        String name;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

}

执行结果:

key: 1, value:User{id=1, name='user_1'}
key: 2, value:User{id=2, name='user_2'}
key: 3, value:User{id=3, name='user_3'}
key: 4, value:User{id=4, name='user_4'}
key: 5, value:User{id=5, name='user_5'}
key: 6, value:User{id=6, name='user_6'}
key: 7, value:User{id=7, name='user_7'}
key: 8, value:User{id=8, name='user_8'}
key: 9, value:User{id=9, name='user_9'}
key: 10, value:User{id=10, name='user_10'}

 

posted @ 2018-01-29 16:43  艺言弈行  阅读(17100)  评论(0编辑  收藏  举报