Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

How can i create a new array list "onlyRF", and here to print only the books with genre Romance and Fiction, from the array list "books"?

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

		//from this i have to print in new one, only the book with Romance and Fiction genre
		
        AudioBook book = new AudioBook ("Harry Potter", "Joan Rowling",LiteratureGenre.Romance,Locale.ENGLISH,LocalDate.of(2000, 7, 8),
        						"reader1",LocalTime.of(1, 25), 0);
        
        
        AudioBook book1 = new AudioBook ("Inky heart", "Cornelia Funke",LiteratureGenre.Poetry, Locale.UK,LocalDate.of(1965, 12, 5),
								"reader2",LocalTime.of(1, 10), 7);
        
        AudioBook book2 = new AudioBook ("Don Quixote", " Miguel de Cervantes",LiteratureGenre.Romance, Locale.FRENCH,LocalDate.of(1605, 4, 12),
				"reader2",LocalTime.of(4, 25), 0);
        
        Book b1 = new Book("Alisa in Wonderland","Charles Dodgson",LiteratureGenre.Fiction, Locale.GERMAN, LocalDate.of(2019, 1, 1));
   
       
        Book b2 = new Book("Dune", "Frank Herbet",LiteratureGenre.Romance,Locale.ITALIAN, LocalDate.of(2020, 4, 1));


What I have tried:

List<Book> onlyRF = new ArrayList<>();
// this is the one where only the Romance and Fiction book will be
		
       for (Book b:books) {
    	  if(b.getBookGenre().equals(book)) {
    		  System.out.println(b);
    	  }
       }
Posted
Updated 15-Dec-21 5:41am

1 solution

Java
List<Book> onlyRF = new ArrayList<>();
// this is the one where only the Romance and Fiction book will be
		
for (Book b:books) {
    // if Romance or Fiction, add to onlyRF list
    if(b.getBookGenre().equals(LiteratureGenre.Romance) || b.getBookGenre().equals(LiteratureGenre.Fiction) {
        onlyRF.add(b);
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900