将 List 对象转为对象中指定属性的 List 集合_Jaemon-CSDN博客
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
}
public class AnswerApp {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User((long) i, "AnswerAIL" + i, i));
}
// 获取 users 集合中的 id 集合
List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());
System.out.println("ids: " + ids);
System.out.println();
// 获取 users 集合中的 id 集合并转为字符串, 通过 , 拼接
String idsTxt = users.stream().map(User::getId).map(String::valueOf).collect(Collectors.joining(","));
System.out.println("idsTxt: " + idsTxt);
System.out.println();
List<String> names = users.stream().map(User::getName).collect(Collectors.toList());
System.out.println("names: " + names);
System.out.println();
String txt = names.stream().collect(Collectors.joining(","));
System.out.println("txt: " + txt);
System.out.println();
txt = names.stream().collect(Collectors.joining(",", "(", ")"));
System.out.println("txt: " + txt);
}
}
ids: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
idsTxt: 0,1,2,3,4,5,6,7,8,9
names: [AnswerAIL0, AnswerAIL1, AnswerAIL2, AnswerAIL3, AnswerAIL4, AnswerAIL5, AnswerAIL6, AnswerAIL7, AnswerAIL8, AnswerAIL9]
txt: AnswerAIL0,AnswerAIL1,AnswerAIL2,AnswerAIL3,AnswerAIL4,AnswerAIL5,AnswerAIL6,AnswerAIL7,AnswerAIL8,AnswerAIL9
txt: (AnswerAIL0,AnswerAIL1,AnswerAIL2,AnswerAIL3,AnswerAIL4,AnswerAIL5,AnswerAIL6,AnswerAIL7,AnswerAIL8,AnswerAIL9)