File tree Expand file tree Collapse file tree
src/main/java/com/github/hcsp/polymorphism Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package com .github .hcsp .polymorphism ;
22
3+ import java .util .ArrayList ;
34import java .util .Arrays ;
45import java .util .List ;
6+ import java .util .function .Consumer ;
57
68public class User {
7- /** 用户ID,数据库主键,全局唯一 */
9+ /**
10+ * 用户ID,数据库主键,全局唯一
11+ */
812 private final Integer id ;
913
10- /** 用户名 */
14+ /**
15+ * 用户名
16+ */
1117 private final String name ;
1218
1319 public User (Integer id , String name ) {
@@ -31,6 +37,19 @@ public static List<String> collectNames(List<User> users) {
3137 return collector .getNames ();
3238 }
3339
40+ private static class NameCollector implements Consumer <User > {
41+ private final List <String > names = new ArrayList <>();
42+
43+ @ Override
44+ public void accept (User user ) {
45+ names .add (user .getName ());
46+ }
47+
48+ public List <String > getNames () {
49+ return names ;
50+ }
51+ }
52+
3453 public static void main (String [] args ) {
3554 List <User > users = Arrays .asList (new User (1 , "a" ), new User (2 , "b" ));
3655 System .out .println (collectNames (users ));
You can’t perform that action at this time.
0 commit comments