我有这个方法,它接受 n 个参数,并使用几个参数在 arrayList 中搜索一本书。 。 我怎样才能让它变小? 如何按类别或作者对书籍进行排序? 预先感谢您。
这是我的方法 //使用多个条件搜索书籍
static void bookSearch(String... varg) { // take varg as parameter
String title = ""; // place holders
String author = "";
if (varg.length > 1) { // check varg length
title = varg[0]; // if it is greater than 1 initialize needed arguments
author = varg[1];
} else {
title = varg[0]; // else initialize the first argument
}
for (Book book : bookList) {
/*
* if the title is the same and there is a second argument that
* match author's name print found it
*/
if (book.getTitle().equals(title)) {
if (author.isEmpty() ^ (book.getAuthor().getfName() == author)) {
System.out.println(" \"" +
title +
"\" founded at: " +
bookList.indexOf(book));
break;
}// end of if
} else if (bookList.indexOf(book) == bookList.size() - 1) {// if not found
System.out.println("cant find \"" + title);
}// end of else
} // end of for loop
} //end of search method
最佳答案
在Java8
中,您可以使用lambda和函数来获得灵活的filter
书籍函数。
例如您有以下 Book
类(class):
class Book {
private String author;
private String title;
}
图书过滤器
函数可能如下所示:
BiFunction<List<Book>, Predicate<Book>, List<Book>> BOOK_FILTER =
(books, fields) -> books.stream().filter(fields).collect(Collectors.toList());
然后,您只需构建所需的谓词
并使用此函数即可。
public static List<Book> findBookByPredicate(List<Book> books, String author, String title) {
Predicate<Book> byAuthor = book -> book.getAuthor().equals(author);
Predicate<Book> byTitle = book -> book.getTitle().equals(title);
return BOOK_FILTER.apply(books, byAuthor.and(byTitle));
}
如您所见,您不仅限于特定数量的 Book
字段。你可以随意组合; BOOK_FILTER
功能保持不变。
关于java - 在java中使用多个条件搜索书籍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462114/