我是 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?
慕斯王
相关分类