user2686811
user2686811

Reputation: 629

Java search list of objects for variable

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.

Upvotes: 2

Views: 5358

Answers (3)

rocketboy
rocketboy

Reputation: 9741

Maybe this is off topic, but when solving such problems, having objects with nested lists, though logically simple, is a really bad idea. Its extremely hard to maintain, scale and work with.

If you use this structure throughout and come across a problem like:

Give me all the books written by this author.

You are toast, you will have to iterate over each and every book. Or start maintaining caches and what not. It gets worse when the nesting deepens.

Lets say, now you need to maintain each Author's list of hobbies too. Think of how would you implement something like : Give me all the books whose authors like skydiving!

I know this doesn't answer your question. Just my 2 cents.

Upvotes: 1

qqilihq
qqilihq

Reputation: 11474

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.

Upvotes: 8

Fly
Fly

Reputation: 872

Something primitive:

List<Author> authors;
...
Iterator<Author> ai = authors.iterator();
Author a;
while(ai.hasNext()){
    a = ai.next();
    if(a.name.equalsIgnoreCase(yourname)){
       return a;
    }
    continue;
}

Edit: Too late :/

Upvotes: 0

Related Questions