【发布时间】:2021-08-16 02:59:06
【问题描述】:
有没有一种从包含字符串字段的列表中获取字符串列表的有效方法。
即 我有客户对象和约会对象
public Customer {
String customerId;
String name;
List<Appointment> appointments;
public String getCustomerId() {return customerId;}
public String getName() {return name;}
public List<Appointment> getAppointments() {return appointments;}
}
public Appointments {
String appointmentId;
String employee;
}
现在作为客户,我可以有几个不同的约会。如果我只想获取与客户关联的所有约会 ID 的列表怎么办?
类似 -> customer.getAppointments().getId;?
【问题讨论】:
-
应该接近
customer.getAppointments().stream().map(a -> a.appointmentId).collect(toList()) -
你的意思是在性能方面高效还是基于可读性?在我看来,流是最易读的选项(一旦你习惯了这个符号)。符号
map(a -> a.appointmentId)甚至可以替换为map(a::appointmentId)。结果相同,符号不同。
标签: java list arraylist collections