【问题标题】:To get list of member from list of objects using Streams java [duplicate]使用Streams java从对象列表中获取成员列表[重复]
【发布时间】:2017-09-29 18:55:52
【问题描述】:

我有一个包含两个成员的类和该类的对象列表。现在我想从对象列表中提取成员列表。

例如:

class student {
      int Id;
      String studentName;
}

现在我需要从学生列表中检索学生姓名列表。 java8 Streams如何做到这一点?

不使用流的解决方案:

List<student> studentList;
List<String> nameList = new ArrayList<String>();
Iterator iterator = studentList.iterator();
while(iterator.hasNext()){
  nameList.add(iterator.next().getStudentName());
}

【问题讨论】:

  • 不使用Streams是不是先试了?
  • edit您的问题显示the code you have so far。您应该至少包含您遇到问题的代码的大纲(但最好是minimal reproducible example),然后我们可以尝试帮助解决具体问题。您还应该阅读How to Ask
  • 是的。通过使用列表迭代器并运行循环。

标签: java list object java-stream


【解决方案1】:

你需要使用Stream#map方法,像这样:

List<Student> students = ...;
List<String> names = students.stream().map(Student::getName).collect(toList());

【讨论】:

  • 谢谢。它奏效了
  • @user3425563,如果您觉得其中一个有用的答案,请记得接受并投票。
猜你喜欢
  • 1970-01-01
  • 2015-11-14
  • 2019-06-18
  • 2020-07-10
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 2018-06-21
相关资源
最近更新 更多