Home > OS >  convert array using java 8 stream to an array
convert array using java 8 stream to an array

Time:05-18

it's giving me run time error, while taking BookDetails array out from Book array using stream map.. I tried my best need help? below is the code snippet

    public BookDetails[] getBook(Book[] book) {
           BookDetails[] bookDetails = Arrays.stream(book).map(bookField -> 
           bookField.fields).toArray(size -> new BookDetails[size]);
           return bookDetails;
         }


    public class Book {
    public String title;
    public BookDetails[] fields;
    }

    public class BookDetails {
    @NotNull
    public String id;
    public String title;
   }

CodePudding user response:

You have an array of books that each contains an array of bookdetails so you need to flatmap :

Arrays.stream(book)
      .flatmap(b -> Arrays.stream(b.fields))
      .toArray();

CodePudding user response:

In your method BookDetails[] getBook(Book[] book) you have two element having the same name:

  • the method parameter book
  • the lambda parameter book in your java stream

You need to rename one of them to fix your implementation.

CodePudding user response:

First of all I would suggest you to use Collections instead of Array. In any case you can convert it.

Here is an example for you:

public List<BookDetails> getBookDetails(List<Book> books) {
        if (CollectionUtils.isEmpty(books)) {
            return Collections.emptyList();
        }
        return books
            .stream()
            .flatMap(b -> Arrays.stream(b.fields))
            .toList();
    }

CodePudding user response:

The first error is found in the Steam map() function. You have defined the argument (book) equal to the function parameter. Correct the function from

public BookDetails[] getBook(Book[] book) {
      BookDetails[] bookDetails = Arrays.stream(book).map(book -> 
         book.fields).toArray(size -> new BookDetails[size]);
       return bookDetails;
}

to

public BookDetails[] getBook(Book[] book) {
      BookDetails[] bookDetails = Arrays.stream(book).map(b-> 
         b.fields).toArray(size -> new BookDetails[size]);
       return bookDetails;
}
  • Related