Last active
December 25, 2017 05:23
-
-
Save dusanstanojeviccs/0c8c28fea15dfb2d7f72136b50eb79d6 to your computer and use it in GitHub Desktop.
BookRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package repositories; | |
| import com.google.inject.Singleton; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import java.util.Optional; | |
| import java.util.stream.Collectors; | |
| @Singleton | |
| public class BookRepository { | |
| private List<Book> bookList = new ArrayList<>(); | |
| public List<Book> findAll() { | |
| return bookList; | |
| } | |
| public Optional<Book> findById(int id) { | |
| return bookList.stream().filter(book -> book.getId() == id).findFirst(); | |
| } | |
| public void delete(int id) { | |
| bookList = bookList.stream().filter(book -> book.getId() != id).collect(Collectors.toList()); | |
| } | |
| public void add(Book book) { | |
| if (!findById(book.getId()).isPresent()) { | |
| bookList.add(book); | |
| } | |
| } | |
| public void update(Book book) { | |
| Optional<Book> bookOptional = findById(book.getId()); | |
| if (bookOptional.isPresent()) { | |
| Book bookToUpdate = bookOptional.get(); | |
| bookToUpdate.setDescription(book.getDescription()); | |
| bookToUpdate.setTitle(book.getTitle()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment