我是 Java 8 的新手。我需要使用以下方法在 Java 8 中创建一个字符串数组:我有如下所述的学校、主题、出版商、书籍的 Pojos -public class School { private Subject[] subjects; public Subject[] getSubjects() { return subjects; } public void setSubjects(Subject[] subjects) { this.subjects = subjects; }}public class Subject { private String subjectName; private String subjectId; private Publisher publisher; public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getSubjectId() { return subjectId; } public void setSubjectId(String subjectId) { this.subjectId = subjectId; } public Publisher getpublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; }}public class Publisher{ private String name; private String sinNo; private Book[] books; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSinNo() { return sinNo; } public void setSinNo(String sinNo) { this.sinNo = sinNo; } public Book[] getBooks() { return books; } public void setBooks(Book[] books) { this.books = books; }}public class Book { private String bookName; private String bookId; public String getBookName() { return bookName; }现在我的要求是制作一个数组,其中包含我拥有的 School 对象中的所有 bookId。旧的 java 代码下面是必需的代码public static void main(String[] args) { List<String> list = new ArrayList<>(); School first = <<School Object>>; for(Subject sub : first.getSubjects()){ Publisher p = sub.getpublisher(); for(Book b : p.getBooks()) { list.add(b.getBookId()); } } //desired result String[] bookIds = (String[]) list.toArray();}}这可以使用 Java 8 流、收集器、映射来完成吗?另外,如果我们只想获得那些奇数/偶数的图书 ID?
1 回答
慕斯王
TA贡献1864条经验 获得超2个赞
是的 - 你需要一个flatMap来实现这个
Stream.of(first.getSubjects()) .map(Subject::getPublisher) .map(Publisher::getBooks) .flatMap(Arrays::stream) .map(Book::getBookId) .collect(Collectors.toList());
如果你想让它null 安全,你需要添加额外的过滤,比如
List<String> collect = Stream.of(first.getSubjects()) .map(Subject::getPublisher) .filter(Objects::nonNull) // filter all null publishers .map(Publisher::getBooks) .filter(Objects::nonNull) // filter all null book lists .flatMap(Arrays::stream) .map(Book::getBookId) .filter(Objects::nonNull) // filter all null book ids .collect(Collectors.toList());
添加回答
举报
0/150
提交
取消