java - 在java中使用多个条件搜索书籍

标签 java

我有这个方法,它接受 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/

相关文章:

java - oracle.jdbc.ReadTimeout 和 Socket 读取超时

java - 线程中出现异常 "main"java.rmi.NotBoundException

java - 正在为 servlet 配置 'clean' 使用 VM 参数?

java - 将java文件写入C盘访问错误

java - 使用 Fmeasure 进行引导的评分模式

java - 使用三元运算符时出错

java - 为什么泛型类型参数上的注释对于嵌套类型不可见?

Java 将传递给方法的对象转换为其原始类型

java - 大数模 n 的快速乘法

java - 检测CPU型号信息