Kyle Kyle - 27 days ago 11
Java Question

Display specific items from an array that meet certain critera

I'm having an issue with pulling specific items from an array and displaying them if they are an item that meets a certain criteria.

Some context, I have an array named Person that is populated using an excel file. Each item in the array has multiple attributes such as firstName, lastName, and favoriteColor. I need to be able to just print out on the console all the people who have the favoriteColor of Green.

As of now I have it so that it will display everybody but I'm working on cutting it down to just show people with Green as their favorite color. The area I believe is causing issues looks something like this.

for (final Person person : people) {
//System.out.println(person);
for (favoriteColor == "Green");
System.out.println(person);
}


I understand that something is wrong with my favoriteColor == "Green" line. I'm not used to Java that much so this is just kind of confusing me. Do any of you have any insight on this?

Thanks

Answer

You need to run if condition inside for loop to filter out your data. You should do something like:

 for (Person person : people) {
        if(person.getFavoriteColor().equalsIgnoreCase("Green")){
                  System.out.println(person.getFirstName());
            }
        }

You can add more than one if condition.

Comments