从 ArrayList 中的对象中搜索特定元素

我在这里创建了一个类:


class book{

    String book_nm;

    String author_nm;

    String publication;

    int price;

    book(String book_nm,String author_nm,String publication,int price){

        this.book_nm=book_nm;

        this.author_nm=author_nm;

        this.publication=publication;

        this.price=price;

    }

}

现在我想根据作者和书名搜索特定值


ArrayList<book> bk = new ArrayList<book>();

我使用 switch case 创建了一个菜单驱动程序


case 3: System.out.println("Search:"+"\n"+"1.By Book Name\n2.By Author Name");

                    Scanner s= new Scanner(System.in);

                    int choice=s.nextInt();

                    while(choice<3){

                        switch(choice){

                            case 1:System.out.println("Enter the name of the book\n");

                                    String name=s.next();

                                    -------

                            case 2:System.out.println("Enter the name of the author\n");

                                    String name=s.next();       ------


                        }

                    }

我知道如何在 ArrayList 中查找和搜索特定元素,但不知道如何查找对象。


扬帆大鱼
浏览 995回答 3
3回答

MYYA

下面的代码返回一个列表,基于您的search (filter):List< Book> result = bk.stream().filter(book -> "booknamehere".equals(book.getBook_nm()))&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;.filter(book -> "authernamehere".equals(book.getAuther_nm()))&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;.collect(Collectors.toList());

www说

首先有一种新方法(使用 java 8+)和旧方法来做到这一点。新方法将是这样的:String authorName =&nbsp; s.next();String bookName = s.next();List<String> result = bk.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // open stream&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(book-> book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName ) )&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());另一种(老式)方法是使用 for 循环:ArrayList<book> result = new ArrayList<book>();for(Book book : bk) //By the way always use Big first letter for name of your Class! (Not book but Book){&nbsp; &nbsp; &nbsp;if(book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName))&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(book);&nbsp;&nbsp; &nbsp; &nbsp;}}在这之后,您可以在这两种情况下打印包含该书的结果列表。但是,如果您要搜索很多此作者和书名,并且您有很多元素,则可以考虑检查性能。因为每次搜索都会遍历列表。也许使用 Map 有更好的解决方案......一些额外的信息。如果您知道是否总是只能从条件中找到一个元素,则它是重要的。例如,在您的情况下,您可以唯一找到一本书,其中名称 X 和作者 Y。不能有另一本书具有相同的名称和作者。在这种情况下,您可以这样做:新方法(Java 8 之后):&nbsp;Book res = bk.stream().filter(book -> book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName)).findFirst().get();旧方法:Book result = null;for(Book book : bk){&nbsp; &nbsp; &nbsp;if(book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName))&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = book;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;}}这样搜索一个元素时速度会更快
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java