有没有一种从对象列表中获取字符串列表的有效方法?

Mar*_*nho 1 java collections list arraylist

是否有一种有效的方法可以从包含字符串字段的列表中获取字符串列表。

即我有客户对象和约会对象

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;
}
Run Code Online (Sandbox Code Playgroud)

现在,作为客户,我可以有几个不同的约会。如果我只想获得与客户关联的所有约会 ID 的列表怎么办?

类似于 -> customer.getAppointments().getId;?

Ans*_*den 5

通过使用流api:

List<String> idList = someCustomer.getAppointments()
    .stream()
    .map(Appointment::getId)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

  • 他看起来对流不太熟悉,如果你添加 toList 的静态导入,或者只使用“Collectors”,也许可以帮助他。... (2认同)
  • 从 JDK 16 开始,您应该只在流上调用“toList()”,而不是“collect(Collectors.toList())”。 (2认同)