
现有如下需求:
将List<User> 转换为List<IdAndName>类型
具体的实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
public class TestListTransform { public static List<User> users = new ArrayList<>();
static { for (int i = 0; i < 10; i++) { users.add(new User(i, "tck" + i, i + 2, "[email protected]")); } }
public static void main(String[] args) { List<IdAndName> collect = users.stream() .map(user -> new IdAndName(user.getId(), user.getName())) .collect(Collectors.toList()); System.out.println(collect); } }
|
实体类User
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
public class User { private Integer id; private String name; private Integer age; private String email;
public User() { }
public User(Integer id, String name, Integer age, String email) { this.id = id; this.name = name; this.age = age; this.email = email; }
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; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } }
|
实体类IdAndName
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class IdAndName { private Integer id; private String name;
public IdAndName() { }
public IdAndName(Integer id, String name) { this.id = id; this.name = 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 "IdAndName{" + "id=" + id + ", name='" + name + ''' + '}'; } }
|
近期评论