Skip to content

Commit fd2efb3

Browse files
authored
练习 (#141)
练习 (#141)
1 parent cb252e2 commit fd2efb3

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

  • src/main/java/com/github/hcsp/polymorphism

src/main/java/com/github/hcsp/polymorphism/User.java

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
package com.github.hcsp.polymorphism;
22

3+
import java.util.ArrayList;
34
import java.util.Arrays;
45
import java.util.List;
6+
import java.util.function.Consumer;
57

68
public 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));

0 commit comments

Comments
 (0)