Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java search list of objects for variable

Tags:

java

list

I have a List of Book

List<Book> books = new ArrayList<Book>();

public class Book {
    String name;
    List<Author> authors;
}

Book contains a List of Author which contains an ID, Name and Age

public class Author {
    int ID;
    String Name;
    int Age;
}

I can iterate through the books List and return the Book where Name = x but I'm not sure how I can search Author and return where Name = y.

like image 615
user2686811 Avatar asked Jul 23 '26 11:07

user2686811


1 Answers

Add a method hasAuthor(String) to your Book which loops through the List<Author> list and compares the name. Like so:

boolean hasAuthor(String name) {
    for (Author author : authors) {
        if (author.name.equals(name)) {
            return true;
        }
    }
    return false;
}

To find books with a specific author, you loop over the List<Book> and invoke the hasAuthor(String) method.

like image 100
qqilihq Avatar answered Jul 26 '26 14:07

qqilihq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!