java-从另一个列表的子属性创建列表

java-从另一个列表的子属性创建列表,java,java-8,Java,Java 8,我用ORM定义了三个类及其getter和setter,如下所示: class Author { Integer id; String name; } class BookAuthor { Integer id_book; Author author; } class Book { String title; List<BookAuthor> authors; } 类作者{ 整数id; 字符串名; } 班级图书作者{ 整型id_书; 作者; } 课堂用书{

我用ORM定义了三个类及其getter和setter,如下所示:

class Author {
  Integer id;
  String name;
}

class BookAuthor {
  Integer id_book;
  Author author;
}

class Book {
  String title;
  List<BookAuthor> authors;
}
类作者{
整数id;
字符串名;
}
班级图书作者{
整型id_书;
作者;
}
课堂用书{
字符串标题;
列出作者名单;
}
我想从教科书中创建一个id_作者列表。 我发现一种方法是使用流。我试过这个:

List<Integer> result = authors.stream().map(BookAuthor::getAuthor::getId).collect(Collectors.toList());
List result=authors.stream().map(BookAuthor::getAuthor::getId).collect(Collectors.toList());
但它似乎不起作用。 我可以访问Author类中的“id”属性吗

编辑: 也许一种方法是:

List<Author> authorList = authors.stream().map(BookAuthor::getAuthor).collect(Collectors.toList());
List<Integer> result = authorList.stream().map(Author::getId).collect(Collectors.toList());
List authorList=authors.stream().map(BookAuthor::getAuthor.collect(Collectors.toList());
List result=authorList.stream().map(Author::getId).collect(Collectors.toList());

谢谢。

我假设
authors
变量是BookAuthor的列表(或集合),而不是Author(基于您的代码)

我认为你的想法是对的,我只是认为你不能链接
操作符

因此,请尝试使用lambda:

authors.stream().
     map(ba -> ba.getAuthor().getId()).
     collect(Collectors.toList());
公共类示例{
公共静态void main(字符串[]args){
Book book1=新书();book1.authors=新ArrayList();
author1=新作者();author1.id=5;
bookAuthor1=newbookauthor();bookAuthor1.author=author1;
book1.authors.add(bookAuthor1);
List idList=book1.authors.stream().map(ba->ba.author.id).collect(Collectors.toList());
}
}

您不能像这样链接方法引用。但您可以使用
map
功能两次:

authors.stream()
   .map(BookAuthor::getAuthor)
   .map(Author::getId)
   .collect(Collectors.toList());

我错过了什么是bahere@Alex这是BookAuthor的例子。它表示要映射的流的特定元素。如果您愿意,您可以编写BookAuthor ba,但您不必这样做,因为Java会推断出这一点
authors.stream()
   .map(BookAuthor::getAuthor)
   .map(Author::getId)
   .collect(Collectors.toList());