Skip to content

Instantly share code, notes, and snippets.

@marcrovi
Created May 15, 2020 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcrovi/74595b22b9b66a878ca08f5dcb3e793b to your computer and use it in GitHub Desktop.
Save marcrovi/74595b22b9b66a878ca08f5dcb3e793b to your computer and use it in GitHub Desktop.
Medium Final Example
import java.util.List;
import java.util.*;
public class FinalExample{
public static void main(String[] args){
List<Book> listBooks = new ArrayList<Book>();
//Create 4 Harry Potter books
Book harryPotter1 = new Book();
harryPotter1.setTitle("Harry Potter and The Philosopher's Stone");
harryPotter1.setAuthor("J.K. Rowling");
harryPotter1.setNumOfPages(296);
Book harryPotter2 = new Book();
harryPotter2.setTitle("Harry Potter and The Chamber of Secrets");
harryPotter2.setAuthor("J.K. Rowling");
harryPotter2.setNumOfPages(301);
Book harryPotter3 = new Book();
harryPotter3.setTitle("Harry Potter and The Prisoner of Azkaban");
harryPotter3.setAuthor("J.K. Rowling");
harryPotter3.setNumOfPages(426);
Book harryPotter4 = new Book();
harryPotter4.setTitle("Harry Potter and The Goblet of Fire");
harryPotter4.setAuthor("J.K. Rowling");
//Add the books to the list
listBooks.add(harryPotter1);
listBooks.add(harryPotter2);
listBooks.add(harryPotter3);
listBooks.add(harryPotter4);
FinalExample ex = new FinalExample();
ex.filterBooks(listBooks);
}
private Boolean validate (int numOfPages){
if(numOfPages > 300){
return true;
}
return false;
}
public List<Book> filterBooks(List<Book> listBooks){
List<Book> filteredList= new ArrayList<Book>();
for(Book book: listBooks){
if(validate(book.getNumOfPages())){
filteredList.add(book);
System.out.println(book.getTitle());
}
}
return filteredList;
}
}
class Book{
private String title;
private String author;
private int numOfPages;
public Book(){ //Constructor
this.title= "";
this.author= "";
this.numOfPages = 0;
}
public void setTitle(String title){
this.title= title;
}
public String getTitle(){
return this.title;
}
public void setAuthor(String author){
this.author= author;
}
public String getAuthor(){
return this.author;
}
public void setNumOfPages(int numOfPages){
this.numOfPages= numOfPages;
}
public int getNumOfPages(){
return this.numOfPages;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment