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
-
1Please pick up a book on Java or read the docs/tutorial. – uncaught_exception May 05 '16 at 13:50
-
We don't write code for you here, and you read that in the welcome page for this site (or should have as you have the metal that says you did). – Rabbit Guy May 05 '16 at 13:50
-
Have you tried implementing anything? have you tried searching StackOverflow? – Fjotten May 05 '16 at 13:52
3 Answers
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.

- 61
- 3
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);

- 109
- 4
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.
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 (item.toLowercase().contains(searchString.toLowercase()))

- 213,210
- 22
- 193
- 313