简体   繁体   English

如何在 ArrayList 中搜索对象?

[英]How to search for an Object in ArrayList?

I want search for an object in an arraylist using one of it attribute: String name.我想使用以下属性之一在数组列表中搜索对象:字符串名称。

I have printed out Item Found here, and this works just fine.我已经打印了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]");
        }
    }
}

However, I want to notify when the item is not found as well.但是,我也想在未找到该项目时发出通知。 When I add else to this for loop, the String itemSeacrh gets matched (might not be the exact right term, sorry) with all the objects in the arraylist, and prints out the notification for every object index.当我向这个for循环添加elseString itemSeacrh与 arraylist 中的所有对象匹配(可能不是正确的术语,抱歉),并打印出每个对象索引的通知。

Let me explain.让我解释。 Suppose, objects : book, pen and pencil are stored in the ArrayList itemList in that respective order and, the for loop is modified the following way:假设对象:书本、笔和铅笔按各自的顺序存储在 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]");
        }
    }

I want to search for the book.我想找书。 When I enter book as the itemSearch the following get printed in the console:当我输入 book 作为itemSearch时,控制台会打印以下内容:

                SEARCH ITEMS
Enter item name:
book
                [ITEM FOUND]
                [ITEM NOT FOUND]
                [ITEM NOT FOUND]

As you can see, it checks and prints that the book is not found in other objects, which in not what I exactly had in mind.如您所见,它会检查并打印出在其他对象中没有找到这本书,这不是我真正想到的。 I want it to print item found or either item not found , not both at the same time.我希望它打印item founditem not found ,而不是同时打印。

Thank you.谢谢你。 I hope you understand my query.我希望你能理解我的查询。

The easiest way to do this is to print when you have found the book, and return.最简单的方法是在找到书后打印,然后返回。 This way you will stop iterating once the book is found, and leave the function immediatly:这样,一旦找到书,您将停止迭代,并立即离开该函数:

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]");

This will not allow you to do any further processing of the book after finding, so you may want to store the book in a variable outside the loop, and execute some code in a conditional:这将不允许您在查找后对书进行任何进一步处理,因此您可能希望将书存储在循环外的变量中,并在条件中执行一些代码:

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

As a final note, look into using for-each loops as they are generally easier to read and faster than typical for loops:最后,请考虑使用for-each循环,因为它们通常比典型的 for 循环更容易阅读且速度更快

for (Item item: itemList) {
    // do some stuff ...
}

created the list and the search item:创建列表和搜索项:

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

then the item check function is那么项目检查功能是

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

and it's working for me, please try this and let us know :)它对我有用,请试试这个,让我们知道:)

All other methods mentioned by other users seems good.其他用户提到的所有其他方法似乎都不错。 Just to expose you to something new, here's my 2 cents.只是为了让您接触新事物,这是我的 2 美分。 You could use Java Stream API to find any that matches your search term.您可以使用Java Stream API查找与您的搜索词匹配的任何内容。 I find it more readable but it is my personal preference.我觉得它更具可读性,但这是我个人的喜好。

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]");
        }
    }
}

And if you want to get the actual first item, then you could use如果你想获得实际的第一项,那么你可以使用

Item foundItem = itemList
    .stream()
    .filter((item) -> item.name.equalsIgnoreCase(itemSearch))
    .findFirst()
    .orElse(null);
System.out.println(foundItem);

there are many ways to search for an item so after adding the items to the list use a string to compare with the original item so if the item is not found a statement will be printed after the loop ends有多种搜索项目的方法,因此在将项目添加到列表后,使用字符串与原始项目进行比较,因此如果未找到该项目,将在循环结束后打印一条语句

 System.out.println("Enter an item to search for:");
    String item = sc.nextLine();
    String notFound = null;

here is the code i used to search for a "String" in a list using the " matches " method这是我用来使用“匹配”方法在列表中搜索“字符串”的代码

 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.

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