简体   繁体   English

从ArrayList对象中搜索特定元素

[英]Search for a particular element from object in ArrayList

Here I have created a class: 在这里,我创建了一个类:

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;
    }
}

Now I want to search for particular value according to author and book name 现在我想根据作者和书名来搜索特定的值

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

I have created a menu driver using 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();       ------

                        }
                    }

I know how to find and search for a particular element in ArrayList but not for objects. 我知道如何在ArrayList中查找和搜索特定元素,但不查找对象。

Using for loop over ArrayList can solve your problem, it's naive method and old fashioned. 在ArrayList上使用for循环可以解决您的问题,这是一种幼稚的方法并且过时。

Below is the code for it. 下面是它的代码。

import java.util.ArrayList;

public class HelloWorld{

     public static void main(String []args){
        String author_name = "abc";
        ArrayList<book> bk = new ArrayList<book>();
        bk.add(new book("abc", "abc", "abc", 10));
        bk.add(new book("mno", "mno", "abc", 10));
        bk.add(new book("xyz", "abc", "abc", 10));
        ArrayList<book> booksByAuthor = new ArrayList<book>();
        for(book obj : bk)
        {
            if(obj.author_nm == author_name)
            {
                booksByAuthor.add(obj);
            }
        }

     }
}

class book{
      public String book_nm;
      public String author_nm;
      public String publication;
      public int price;
      public 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;
      }
}

Hope you can get an idea from it. 希望您能从中得到启发。

Below code return a list, based on of your search (filter) : 下面的代码基于您的search (filter)返回一个列表:

List< Book> result = bk.stream().filter(book -> "booknamehere".equals(book.getBook_nm()))    
   .filter(book -> "authernamehere".equals(book.getAuther_nm()))    
   .collect(Collectors.toList());

First there is a new ways (With java 8+) and old way to do this. 首先,有一种新方法(使用Java 8+)和旧方法可以做到这一点。 The new ways will be something like this: 新方法将如下所示:

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());

Another (old fashioned) way is with for loop: 另一种(老式的)方法是使用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); 
     }
}

After this you can print in both cases the result list containing the book. 之后,您可以在两种情况下都打印包含书籍的结果列表。 But if you will search a lot of this author and book name and you have a lots of elements you can think check the performance. 但是,如果您要搜索大量的作者和书名,并且有很多内容,您可以考虑检查一下性能。 Because every search will loop over the list. 因为每次搜索都将遍历列表。 Maybe there is better solution using Map ... 也许使用Map有更好的解决方案...

Some additional information. 一些其他信息。 It is import if you know if there is always only one element that will be found from the criteria. 如果您知道从条件中始终只能找到一个元素,则为导入。 For example in your case you unique find one book where has name X and author Y. There can not be another book with the same name and author. 例如,在您的情况下,您唯一地找到一本名为X和作者Y的书。不能再有另一本具有相同名称和作者的书。 In such cases you can do like this: 在这种情况下,您可以这样:

New way (after java 8): 新方法(在Java 8之后):

 Book res = bk.stream()
.filter(book -> book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName))
.findFirst()
.get();

old way: 旧方法:

Book result = null;
for(Book book : bk)
{
     if(book.getBook_nm().equals(bookName) && book.getAuthor_nm().equals(authorName))
     {
          result = book;
          break;
     }
}

This way it is faster when you search one element 这样,搜索一个元素时速度更快

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM