[英]How to search for an Object in ArrayList?
我想使用以下屬性之一在數組列表中搜索對象:字符串名稱。
我已經打印了Item Found here,這很好用。
public static void searchItems() {
// variable declaration
String itemSearch;
// collect value of variable using Scanner class
System.out.println("\t\tSEARCH ITEMS");
System.out.println("Enter item name: ");
itemSearch = input.next();
//search for an item
for (int i=0; i<itemList.size();i++) {
if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
System.out.println("\t\t[ITEM FOUND]");
}
}
}
但是,我也想在未找到該項目時發出通知。 當我向這個for
循環添加else
, String
itemSeacrh
與 arraylist 中的所有對象匹配(可能不是正確的術語,抱歉),並打印出每個對象索引的通知。
讓我解釋。 假設對象:書本、筆和鉛筆按各自的順序存儲在 ArrayList itemList
中,並且for
循環修改如下:
for (int i=0; i<itemList.size();i++) {
if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
System.out.println("\t\t[ITEM FOUND]");
}
else {
System.out.println("\t\t[ITEM NOT FOUND]");
}
}
我想找書。 當我輸入 book 作為itemSearch
時,控制台會打印以下內容:
SEARCH ITEMS
Enter item name:
book
[ITEM FOUND]
[ITEM NOT FOUND]
[ITEM NOT FOUND]
如您所見,它會檢查並打印出在其他對象中沒有找到這本書,這不是我真正想到的。 我希望它打印item found或item not found ,而不是同時打印。
謝謝你。 我希望你能理解我的查詢。
最簡單的方法是在找到書后打印,然后返回。 這樣,一旦找到書,您將停止迭代,並立即離開該函數:
for (int i=0; i<itemList.size();i++) {
if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
System.out.println("\t\t[ITEM FOUND]");
return;
}
}
System.out.println("\t\t[ITEM NOT FOUND]");
這將不允許您在查找后對書進行任何進一步處理,因此您可能希望將書存儲在循環外的變量中,並在條件中執行一些代碼:
Item item = null;
for (int i=0; i<itemList.size();i++) {
if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
item = itemList.get();
break;
}
}
if null != item {
System.out.println("\t\t[ITEM FOUND]");
// do some stuff ...
} else {
System.out.println("\t\t[ITEM NOT FOUND]");
// do some other stuff ...
}
最后,請考慮使用for-each循環,因為它們通常比典型的 for 循環更容易閱讀且速度更快:
for (Item item: itemList) {
// do some stuff ...
}
創建列表和搜索項:
List<String> list = new ArrayList<String>();
list.add("book");
list.add("pencil");
list.add("note");
String itemToBeSearched = "book"; // taken as example
if(check(list,itemToBeSearched)){
System.out.println("ITEM FOUND");
}
else
{
System.out.println("NOT FOUND");
}
那么項目檢查功能是
public static boolean check(List<String> list, String itemToBeSearched){
boolean isItemFound =false;
for(String singleItem: list){
if(singleItem.equalsIgnoreCase(itemToBeSearched)){
isItemFound = true;
return isItemFound;
}
}
return isItemFound;
}
它對我有用,請試試這個,讓我們知道:)
其他用戶提到的所有其他方法似乎都不錯。 只是為了讓您接觸新事物,這是我的 2 美分。 您可以使用Java Stream API查找與您的搜索詞匹配的任何內容。 我覺得它更具可讀性,但這是我個人的喜好。
class Item {
String name;
public Item(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
// Mock your senario which you have a search term and
// array of object with a public property 'name'
String itemSearch = "test1";
List<Item> itemList = List.of(new Item("test4"), new Item("test2"), new Item("test3"), new Item("test1"));
boolean searchTermExists = itemList
// Create a stream of items from the item list
.stream()
// Searching if any matches the condition (Predicate) and
// return as soon as we find a match
.anyMatch((item) -> item.name.equalsIgnoreCase(itemSearch));
if(searchTermExists) {
System.out.println("\t\t[ITEM FOUND]");
}else {
System.out.println("\t\t[ITEM NOT FOUND]");
}
}
}
如果你想獲得實際的第一項,那么你可以使用
Item foundItem = itemList
.stream()
.filter((item) -> item.name.equalsIgnoreCase(itemSearch))
.findFirst()
.orElse(null);
System.out.println(foundItem);
有多種搜索項目的方法,因此在將項目添加到列表后,使用字符串與原始項目進行比較,因此如果未找到該項目,將在循環結束后打印一條語句
System.out.println("Enter an item to search for:");
String item = sc.nextLine();
String notFound = null;
這是我用來使用“匹配”方法在列表中搜索“字符串”的代碼
System.out.println("Enter an item to search for:");
String item = sc.nextLine();
String notFound = null;
for (int i = 0; i < list.size(); i++) {
boolean check = list.get(i).matches(item);
if(check){
System.out.println("item is found.");
notFound=item;
break;
}
}
if(notFound == null){
System.out.println("item not found.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.