Reputation: 656
I'm new to Java 8. I need to create a Array of Strings in Java 8 using below:
I've Pojos of School, Subject, Publisher, Book as described below -
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;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
}
Now my ask is to make an Array which has all the bookIds from the School object I have. Below old java code is the required code
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();
}
}
Can this be done using Java 8 streams, Collectors, mappings? Also, if we want to get only those book ids which are odd/even ?
Upvotes: 2
Views: 1863
Reputation: 13571
Yes it is - you need a flatMap to achieve this
Stream.of(first.getSubjects())
.map(Subject::getPublisher)
.map(Publisher::getBooks)
.flatMap(Arrays::stream)
.map(Book::getBookId)
.collect(Collectors.toList());
If you want to have it null safe you need to add additional filtering like
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());
Upvotes: 4