Search code examples
javaarraylistparametersequals

Searching an ArrayList for a matching parameter


I have two classes Museum and Painting. Painting class is working as expected, but I am having issues with the Museum class. The purpose of the method is to return an ArrayList of paintings the museum has, which matches the parameter string.

When I try to compile the code, I am getting lots of error messages and clearly I am not compiling the code correctly.

For example, if there is a Painting by Picasso - it should just return all those paintings and nothing else.

I think I may have missed a step - potentially by creating a local variable to store it in first, but I'm at a bit of a brick wall. I also wonder if String is correct when the ArrayList uses the Painting object.

Does anyone know what I'm missing here?

public class Museum  {
    //creating the fields
    private ArrayList<Painting> paintings;
    private String name;

    /**
     * Create a Museum Class 
     */
    public Museum(String aMuseum) {
        paintings = new ArrayList<>();
        name = aMuseum;
    }

    public String listMatches(String searchString)
    {
        if(filename.equals(searchString)) {
            return filename;
        }
    }
}

Solution

  • Searching paintings by artist should return a sublist of paintings (it may be empty if no painting is found):

    public List<Painting> listMatches(String artist) {
        List<Painting> matches = new ArrayList<>();
        for (Painting painting : paintings) {
            if (artist.equals(painting.getArtist())) {
                matches.add(painting);
            }
        }
    
        return matches;
    }
    

    Stream API may be used for this (more concise and functional style):

    public List<Painting> listMatches(String artist) {
        return paintings.stream()
            .filter(p -> artist.equals(p.getArtist()))
            .collect(Collectors.toList());
    }