Reputation: 425
I have an object (Object 1 for reference) which contains an arraylist of another object (Object 2 for reference).
I want to include a method in Object1, which will take a search term as a parameter and will then iterate through the arraylist of objects2. Through every iteration, it will need to compare the search term against every variable the object has (It has 5 different variable). For example :
The user inputs a search term, the system will then iterate through the arraylists of objects. The first object in the arraylist, it will compare the 5 String variables of that object with the search term, and if there is a single match, it will print that object. It will then move on to the second object in the array list and do the same...
I'm not quite sure how to implement this in a nice readable way. The only way I can think of is implementing multiple IF OR OR statements...
Any ideas ? Any help is appreciated, thanks!
Upvotes: 0
Views: 1737
Reputation: 285440
Say you had a Book class with four Strings:
public class Book {
private String title;
private String publisher;
private String author;
private String isbn;
and you wanted to check if a key String matched any String in this class, you could give Book this method for example:
public boolean containsText(String key) {
// your choice whether to use equals or equalsIgnoreCase
return key.equalsIgnoreCase(title)
|| key.equalsIgnoreCase(publisher)
|| key.equalsIgnoreCase(author)
|| key.equalsIgnoreCase(isbn);
}
Then if you had a List<Book> bookList
and you wanted to display books with matching text you could easily check it with:
public void displayTextMatch(String key) {
// iterate through list
for (Book book : bookList) {
// call Book's containText method
if (book.containsText(key)) {
// assuming Book has a decent `toString()` override:
System.out.println(book);
}
}
}
Upvotes: 1
Reputation: 332
Here is my solution, assuming you are not comfortable with lambdas (java8)
public class MyObject {
public String[] list = {"one", "two", "three", "four"};
public String findMyString(String searchCriteria){
String result= null;
for(int i=0; i<list.length; i++){
if(list[i].equals(searchCriteria) ) return list[i];
}
return result;
}
public static void main(String args[]){
MyObject object = new MyObject();
System.out.println(object.findMyString("zero"));
System.out.println(object.findMyString("one"));
}
}
The output is as follow:
null
one
There are probably more efficient solutions but you are searching with strings and, unless you have a very big dataset, it should not be that big of a performance issue.
Upvotes: 2