Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A search method that finds a string value in an String Array

Tags:

java

So I am trying to create a method that finds a title in a ArrayList of photos.

public class Album {

    private String albumtitle;
    private ArrayList<Photo> photos;

    /**
     * This constructor should initialize the
     * instance variables of the class.
     */
    public Album(String title) {

        this.albumtitle = title;
        photos = new ArrayList<>();

    }

This is the code I have got to for trying to search for a specific title of the photo. I am not sure if i should put (int index) or (String title) in the methods parameters.

public Photo searchByTitle(int index) {

        if (index >= 0 && index < photos.size()) {
            String title = photos.get(index);
            System.out.println(title);
        }
        return null;
    }

I am beginner programmer, and I feel a little guidance will help a lot.

Edit: So lots of people are telling me to use for loops. My project requires me to not do for loops for methods, hence why I have displayed it in this way.

I'll give you an example the lecturer gave us:

https://lms.uwa.edu.au/bbcswebdav/pid-1134902-dt-content-rid-16529804_1/courses/CITS1001_SEM-2_2018/lectures/BooksReadJournal.java.pdf

She doesn't use for loops.


2 Answers

You could use the stream-API:

Arrays.stream(photos).filter(p -> p.getTitle().equalsIgnoreCase(searchTitle)).findFirst().orElseGet(...);

You iterate over each photo called p in this array and compare p's title with the one you search and return the first match.

Or simply use a normal for-loop:

for(int i = 0; i < photos.size(); i++) {
  if(photos[i].getTitle().equalsIgnoreCase(searchTitle)){ return photos[i]; }
  return new ErrorPhoto(); //or some error state
}

More enhanced for-each-loop:

for(Photo p: photos) {
  if(p.getTitle().equalsIgnoreCase(searchTitle)) { return p; }
  return new ErrorPhoto(); //or some error state
}
like image 194
ItFreak Avatar answered Jun 11 '26 17:06

ItFreak


You iterate over each photo and compare its title with the one you search and return the first match:

for(int i = 0; i < photos.size, i++) {
    if(photos.get(i).getTile().equals("title name"){
         System.out.println("Found the title");
    }
}
like image 37
Faraz Avatar answered Jun 11 '26 15:06

Faraz