如何在ArrayList中搜索对象?

huangapple go评论95阅读模式
英文:

How to search for an Object in ArrayList?

问题

我想在一个ArrayList中按照其中一个属性:String名称,搜索一个对象。

我已经在这里打印出*Item Found*,这个部分运行得很好。

    public static void searchItems() {
    // 变量声明
    String itemSearch;
    
    // 使用Scanner类收集变量的值
    System.out.println("    SEARCH ITEMS");
    System.out.println("Enter item name: ");
    itemSearch = input.next();

    // 搜索项目
    for (int i=0; i<itemList.size();i++) {
        if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
            
            System.out.println("    [ITEM FOUND]");
        }
    }
}

然而,我也想在项目*未找到*时进行通知。当我在这个`for`循环中添加`else`时,`String` `itemSeacrh`(可能不是完全准确的术语,抱歉)会与ArrayList中的所有对象匹配,然后为每个对象索引打印出通知。

让我解释一下。假设,*objects*:book,pen和pencil按照相应的顺序存储在ArrayList `itemList`中,并且`for`循环以以下方式进行修改:

for (int i=0; i<itemList.size();i++) {
        if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
            
            System.out.println("    [ITEM FOUND]");
        }
        else {
            System.out.println("    [ITEM NOT FOUND]");
        }
    }

我想要搜索book。当我将book输入为`itemSearch`时,在控制台中会打印出以下内容:

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

正如您所见,它会检查并打印出book在其他对象中*未找到*,这并不是我想要的结果。我希望它要么打印*item found*要么打印*item not found*,而不是同时打印两者。

谢谢。我希望您能理解我的问题。
英文:

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(&quot;\t\tSEARCH ITEMS&quot;);
    System.out.println(&quot;Enter item name: &quot;);
    itemSearch = input.next();

    //search for an item
    for (int i=0; i&lt;itemList.size();i++) {
        if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
            
            System.out.println(&quot;\t\t[ITEM FOUND]&quot;);
        }
    }
}

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&lt;itemList.size();i++) {
        if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
            
            System.out.println(&quot;\t\t[ITEM FOUND]&quot;);
        }
        else {
            System.out.println(&quot;\t\t[ITEM NOT FOUND]&quot;);
        }
    }

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.

答案1

得分: 0

以下是您要翻译的内容:

最简单的方法是在找到书籍时打印出来,然后返回。这样一来,一旦找到书籍,迭代就会停止,然后立即离开函数:

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(i);
        break;
    }
}

if (item != null) {
    System.out.println("\t\t[ITEM FOUND]");
    // 做一些操作...
} else {
    System.out.println("\t\t[ITEM NOT FOUND]");
    // 做一些其他操作...
}

最后,注意使用for-each循环,因为它们通常比传统的for循环更易读,而且更快速

for (Item item : itemList) {
    // 做一些操作...
}
英文:

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&lt;itemList.size();i++) {
    if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
        System.out.println(&quot;\t\t[ITEM FOUND]&quot;);
        return;
    }
}

System.out.println(&quot;\t\t[ITEM NOT FOUND]&quot;);

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&lt;itemList.size();i++) {
    if (itemList.get(i).name.equalsIgnoreCase(itemSearch)) {
        item = itemList.get();
        break;
    }
}

if null != item {
    System.out.println(&quot;\t\t[ITEM FOUND]&quot;);
    // do some stuff ...
} else {
    System.out.println(&quot;\t\t[ITEM NOT FOUND]&quot;);
    // 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 ...
}

答案2

得分: 0

创建了列表和搜索项:

List<String> list = new ArrayList<String>();
list.add("book");
list.add("pencil");
list.add("note");

String itemToBeSearched = "book"; // 以书本为例

if(check(list, itemToBeSearched)){
    System.out.println("找到该项");
}
else
{
    System.out.println("未找到");
}

然后是项检查函数:

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

它对我来说是有效的,请尝试一下并让我们知道结果 如何在ArrayList中搜索对象?

英文:

created the list and the search item:

List&lt;String&gt; list = new ArrayList&lt;String&gt;();
    list.add(&quot;book&quot;);
    list.add(&quot;pencil&quot;);
    list.add(&quot;note&quot;);

    String itemToBeSearched = &quot;book&quot;; // taken as example

    if(check(list,itemToBeSearched)){
        System.out.println(&quot;ITEM FOUND&quot;);
    }
    else
    {
        System.out.println(&quot;NOT FOUND&quot;);
    }

then the item check function is

public static boolean check(List&lt;String&gt; 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 如何在ArrayList中搜索对象?

答案3

得分: 0

除了其他用户提到的方法之外,都是不错的方法。为了让您接触一些新的内容,这里是我的意见。您可以使用Java Stream API来查找与您的搜索词匹配的内容。我认为这样更易读,但这是我的个人偏好。

class Item {
	String name;
	public Item(String name) {
		this.name = name;
	}
}

public class Test {
	public static void main(String[] args) {
        // 模拟您的场景,您有一个搜索词和一个带有公共属性'name'的对象数组
		String itemSearch = "test1";
		List<Item> itemList = List.of(new Item("test4"), new Item("test2"), new Item("test3"), new Item("test1"));

		boolean searchTermExists = itemList
            // 创建一个来自项目列表的项目流
            .stream() 
            // 搜索是否有任何项目与条件(Predicate)匹配,并且
            // 一旦找到匹配项,就立即返回
            .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);
英文:

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 &#39;name&#39;
		String itemSearch = &quot;test1&quot;;
		List&lt;Item&gt; itemList = List.of(new Item(&quot;test4&quot;), new Item(&quot;test2&quot;), new Item(&quot;test3&quot;), new Item(&quot;test1&quot;));

		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) -&gt; item.name.equalsIgnoreCase(itemSearch)); 
		if(searchTermExists) {
			System.out.println(&quot;\t\t[ITEM FOUND]&quot;);
		}else {
			System.out.println(&quot;\t\t[ITEM NOT FOUND]&quot;);
		}
	}
}

And if you want to get the actual first item, then you could use

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

答案4

得分: 0

以下是您要求的代码部分的翻译:

有许多方法可以搜索一个项目
因此在将项目添加到列表之后
使用一个字符串与原始项目进行比较
所以如果没有找到该项目在循环结束后将打印一条语句

System.out.println("输入要搜索的项目:");
String item = sc.nextLine();
String notFound = null;

这是我用来使用matches方法在列表中搜索String的代码

System.out.println("输入要搜索的项目:");
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("找到项目。");
        notFound=item;
        break;
    }
}
if(notFound == null){
    System.out.println("未找到项目。");
}
英文:

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(&quot;Enter an item to search for:&quot;);
    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(&quot;Enter an item to search for:&quot;);
    String item = sc.nextLine();
    String notFound = null;
    
    for (int i = 0; i &lt; list.size(); i++) {
        boolean check = list.get(i).matches(item);
        if(check){
            System.out.println(&quot;item is found.&quot;);
            notFound=item;
            break;
        }
    }
    if(notFound == null){
        System.out.println(&quot;item not found.&quot;);
    }

huangapple
  • 本文由 发表于 2020年8月26日 10:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63589551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定