为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2021-06-09 17:43:00
我在这里创建了一个类: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 中查找和搜索特定元素,但不知道如何查找对象。
查看完整描述

3 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

下面的代码返回一个列表,基于您的search (filter):


List< Book> result = bk.stream().filter(book -> "booknamehere".equals(book.getBook_nm()))    

   .filter(book -> "authernamehere".equals(book.getAuther_nm()))    

   .collect(Collectors.toList());


查看完整回答
反对 回复 2021-06-30
?
www说

TA贡献1775条经验 获得超8个赞

首先有一种新方法(使用 java 8+)和旧方法来做到这一点。新方法将是这样的:


String authorName =  s.next();

String bookName = s.next();

List<String> result = bk.stream()                        // open stream

            .filter(book-> book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName ) ) 

            .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)

{

     if(book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName))

     {

          result.add(book); 

     }

}

在这之后,您可以在这两种情况下打印包含该书的结果列表。但是,如果您要搜索很多此作者和书名,并且您有很多元素,则可以考虑检查性能。因为每次搜索都会遍历列表。也许使用 Map 有更好的解决方案......


一些额外的信息。如果您知道是否总是只能从条件中找到一个元素,则它是重要的。例如,在您的情况下,您可以唯一找到一本书,其中名称 X 和作者 Y。不能有另一本书具有相同的名称和作者。在这种情况下,您可以这样做:


新方法(Java 8 之后):


 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)

{

     if(book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName))

     {

          result = book;

          break;

     }

}

这样搜索一个元素时速度会更快


查看完整回答
反对 回复 2021-06-30
  • 3 回答
  • 0 关注
  • 994 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信