简体   繁体   中英

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.

    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.

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:

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:

                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.

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 (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. You could use Java Stream API to find any that matches your search term. 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.");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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