java 如何在数组列表中搜索项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37052347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search for an item in an arraylist?
提问by Anthony
I am creating a gui that can add,remove and search for a name that a user inputs. I would like to know the code that lets me search for items in the arraylist. Thank you
我正在创建一个 gui,它可以添加、删除和搜索用户输入的名称。我想知道让我在数组列表中搜索项目的代码。谢谢
回答by Santhati Eswar
You can use
您可以使用
Java.util.ArrayList.indexOf(Object)
method it will return the index position of first occurrence of the element in the list.
方法它将返回列表中元素第一次出现的索引位置。
Or
或者
java.util.ArrayList.Contains(Object o)
The above method will return true if the specified element available in the list.
如果指定的元素在列表中可用,则上述方法将返回 true。
回答by Marouane S.
you can do it using predicate to search in a stream representing you list, here is a simple example :
您可以使用谓词在代表您列表的流中进行搜索,这是一个简单的示例:
List<String> listOfUsersName = Arrays.asList("toto", "tata", "joe", "marou", "joana", "johny", "");
String userInputSearch = "jo";
List<String> result =listOfUsersName.stream()
.filter(user -> user.contains(userInputSearch))
.collect(Collectors.toList());
result.forEach(System.out::println);
回答by Sweeper
Since your question did not provide sufficient information, I'll make some things up:
由于你的问题没有提供足够的信息,我会补一些:
//This is your array list that you want to search in:
private ArrayList<String> names = new ArrayList<>(); // Assume this is full of stuff
//This is the user input
private String userInput;
//This method will be called when the search button is clicked
public void onSearchClick() {
}
This is how you are going to implement the search algorithm:
这是您将如何实现搜索算法:
For each item in the array list, if it contains the search string, add it to the search results.
对于数组列表中的每一项,如果它包含搜索字符串,则将其添加到搜索结果中。
That makes a lot of sense, doesn't it?
这很有道理,不是吗?
In code, you would write this:
在代码中,你会这样写:
private ArrayList<String> searchInList(ArrayList<String> list, String searchString) {
ArrayList<String> results = new ArrayList<>();
for (item in list) {
if (item.contains(searchString)) {
results.add(item);
}
}
return results;
}
And then in the onSearchClick
method, you call the search method and do something with the results.
然后在onSearchClick
方法中,你调用搜索方法并对结果做一些事情。
public void onSearchClick() {
ArrayList<String> searchResults = searchInList(names, userInput);
// display the results or whatever
}
If you want a case-insensitive search, you can change the if statement in the search method to this:
如果想要不区分大小写的搜索,可以将搜索方法中的if语句改成这样:
if (item.toLowercase().contains(searchString.toLowercase()))