我想简化这种方法。
你能告诉我怎么做吗?我以某种方式尝试过,但是结果很差。
Books
列表长度未知。可以是10,也可以是0。如果有的话,我需要三本书。
public List<Book> findTheLatest3Books() {
List<Book> books = new ArrayList<>(bookRepository.findAllByOrderByDateOfCreation());
List<Book> listOf3LatestBooks = new ArrayList<>();
if (books.size() >= 3) {
for (int i = 0; i < 3; i++) {
if (books.get(i).isAvailable()) {
listOf3LatestBooks.add(books.get(i));
}
}
}
if (books.size() == 2) {
for (int i = 0; i < 2; i++) {
if (books.get(i).isAvailable()) {
listOf3LatestBooks.add(books.get(i));
}
}
}
if (books.size() == 1) {
for (int i = 0; i < 1; i++) {
if (books.get(i).isAvailable()) {
listOf3LatestBooks.add(books.get(i));
}
}
}
if (books.size() == 0) {
throw new IllegalArgumentException("No books in DB");
}
return listOf3LatestBooks;
}
答案 0 :(得分:5)
通过流:
List<Book> books = ...
if (books.isEmpty()) throw new IllegalArgumentException("No books in DB");
return books.stream() // Stream<Book>
.limit(3) // truncated to be no longer than 3 in length.
.filter(Book::isAvailable) // keep only books that are available
.collect(Collectors.toCollection(ArrayList::new));
这将使用截断长度不超过3
的流,然后进行过滤以保留可用的书。
答案 1 :(得分:3)
如果使用books.size() < 3
,请选择大小,否则使用3
。
if (books.isEmpty()) {
throw new IllegalArgumentException("No books in DB");
}
final int n = books.size() >= 3 ? 3 : books.size();
for (int i = 0; i < n; ++i) {
if (books.get(i).isAvailable()) {
listOf3LatestBooks.add(books.get(i));
}
}
您似乎在使用自定义的Spring JPA存储库方法。您只能获取前3条记录,by limiting query results.
答案 2 :(得分:2)
您可以在i < 3 && i < books.size()
语句中应用条件for
:
public List<Book> findTheLatest3Books() {
List<Book> books = new ArrayList<Book>(bookRepository.findAllByOrderByDateOfCreation());
List<Book> listOf3LatestBooks = new ArrayList<>();
for (int i = 0; i < 3 && i < books.size(); i++) {
if (books.get(i).isAvailable()) {
listOf3LatestBooks.add(books.get(i));
}
}
if (books.size() == 0) {
throw new IllegalArgumentException("No books in DB");
}
return listOf3LatestBooks;
}