【问题标题】:Is there an efficient way of getting a List of Strings from a List of Object?有没有从对象列表中获取字符串列表的有效方法?
【发布时间】: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 -&gt; a.appointmentId).collect(toList())
  • 你的意思是在性能方面高效还是基于可读性?在我看来,流是最易读的选项(一旦你习惯了这个符号)。符号map(a -&gt; a.appointmentId) 甚至可以替换为map(a::appointmentId)。结果相同,符号不同。

标签: java list arraylist collections


【解决方案1】:

通过使用流 api:

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

【讨论】:

  • 他看起来对stream不是很熟悉,如果你添加toList的静态导入可能会对他有所帮助,或者只是使用Collectors....
  • Stream API 比传统的for-loops 慢得多。它们只能用于处理可能导致内存问题的大量数据,例如:扫描包含数百万个文件的文件夹等请阅读此处(blog.jooq.org/2015/12/08/…
  • 从 JDK 16 开始,您应该只在流上调用 toList() 而不是 collect(Collectors.toList())
猜你喜欢
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
相关资源
最近更新 更多