[英]Search for a particular element from object in 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>();
我已經使用開關盒創建了菜單驅動程序
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中查找和搜索特定元素,但不查找對象。
在ArrayList上使用for循環可以解決您的問題,這是一種幼稚的方法並且過時。
下面是它的代碼。
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;
}
}
希望您能從中得到啟發。
下面的代碼基於您的search (filter)
返回一個列表:
List< Book> result = bk.stream().filter(book -> "booknamehere".equals(book.getBook_nm()))
.filter(book -> "authernamehere".equals(book.getAuther_nm()))
.collect(Collectors.toList());
首先,有一種新方法(使用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;
}
}
這樣,搜索一個元素時速度更快
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.