Search code examples
javaooparraylistmethodsreturn-value

How to return multiple objects from a Java Method which are stored in an ArrayList?


I am trying to return all items with the same category name within a list I made myself.

But it is returning only one category item when there are more items with the same category name.

What can I do to return all of them?

I did this method in my item class :

public static String findCategory(List<item>items ,String cat ) { 
    
    for (int i =0 ; i < items.size() ; i++) {
        
        if(items.get(i).getcategory().equals(cat)) 
        {
            return items.get(i).toString();
        }
        
    }
    return "Invalid Category!" ;
}

I am calling this method in my main as :

System.out.println("Enter category name : ");
String categ = input.next() ;
System.out.println(item.findCategory(itemDatabase, categ)) ;

Solution

  • I am trying to return all items with the same category name within a list

    Using Stream it's pretty easy:

    public static List<item> findCategory(List<item> items, String cat) { 
        return items.stream()
          .filter(item -> item.getcategory().equals(cat))
          .collect(Collectors.toList());
    }