diff --git a/src/main/java/com/github/hcsp/polymorphism/User.java b/src/main/java/com/github/hcsp/polymorphism/User.java index 78d927d..3f50bc1 100644 --- a/src/main/java/com/github/hcsp/polymorphism/User.java +++ b/src/main/java/com/github/hcsp/polymorphism/User.java @@ -1,13 +1,19 @@ package com.github.hcsp.polymorphism; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Consumer; public class User { - /** 用户ID,数据库主键,全局唯一 */ + /** + * 用户ID,数据库主键,全局唯一 + */ private final Integer id; - /** 用户名 */ + /** + * 用户名 + */ private final String name; public User(Integer id, String name) { @@ -31,6 +37,19 @@ public static List collectNames(List users) { return collector.getNames(); } + private static class NameCollector implements Consumer { + private final List names = new ArrayList<>(); + + @Override + public void accept(User user) { + names.add(user.getName()); + } + + public List getNames() { + return names; + } + } + public static void main(String[] args) { List users = Arrays.asList(new User(1, "a"), new User(2, "b")); System.out.println(collectNames(users));