Creating a new array with selected elements of another array

Foreword: I'm terrible with java and just learning. I was looking for a ton, I could not find the answer. We CANNOT use arraylists.

I have a Book class that contains information in a specific book, such as a page, author, etc.

I have a Bookshelf class that reads in an array of Book objects. I need to write a method that takes the name of the author, finds all the books in the book array belonging to this author, and then returns an array of these books.

My plan is to find the total number of books by this author and store it in a variable. Then create a new array of this size. I just donโ€™t know how to select elements from the Book array and put them in a new array.

What I still donโ€™t know is it right ...

public Book[] getBooksByAuthor(String author) {
    int count = 0;
    String a  = author;

    for(int i = 0; i < books.length; i++){
        if(books[i].getAuthor().equals(a)){
            count += 1;
        }
    }
+4
3

Java 8 :

public Book[] getBooksByAuthor(String author) {
    return Arrays.stream(books)
                 .filter(b -> b.getAuthor().equals(author))
                 .toArray(Book[]::new);
}
+4

:

public Book[] getBooksByAuthor(String author) {
    int count = 0;
    String a  = author;
    int iter = 0;

    for(int i = 0; i < books.length; i++){
        if(books[i].getAuthor().equals(a)){
            count += 1;
        }
    }
    Book[] newBooks = new Book[count];
    for (int i = 0; i < books.length; i++){
        if(books[i].getAuthor().equals(a)){
            newBooks[iter] = books[i];
            iter += 1;

        }
    }
    return newBooks;
}
+1

, :

String booksFromAuthor = "";
for(final String book : books){
    if(book.equals(author))
        booksFromAuthor += book + "|";
}
return booksFromAuthor.split("|");
0
source

Source: https://habr.com/ru/post/1687122/


All Articles