Robert Vasile
Robert Vasile

Reputation: 121

Filter a List of objects using Stream

I have a list of objects. I want to create another list in which to add certain objects from the created list. I want to use Stream-filter, but I don't understand where I'm wrong. Any suggestions? Thank you very much.

Initial list:

 final List<CategoryModel> categoryList = doSearch(query, params, CategoryModel.class);
    

List with objects filtered from first list:

List<CategoryModel> sitemapList = (List<CategoryModel>) categoryList.stream().filter(categoryModel -> selectCategoryForSitemap(categoryModel));

Function for filter objects:

private boolean selectCategoryForSitemap(CategoryModel categoryModel){
    if(categoryModel.getMetaRobots() != null) {
        if (categoryModel.getMetaRobots() == CmsRobotTag.INDEX_FOLLOW || categoryModel.getMetaRobots() == CmsRobotTag.INDEX_NOFOLLOW) {
            return Boolean.TRUE;
        }
    }else if (categoryModel instanceof BrandCategoryModel || categoryModel instanceof CategoryModel) {
        if(!categoryModel.getCode().equals("1")) {
            return Boolean.TRUE;
        }
    }
    return Boolean.FALSE;
}

Upvotes: 0

Views: 261

Answers (2)

talex
talex

Reputation: 20542

List<CategoryModel> sitemapList = categoryList.stream()
    .filter(categoryModel -> selectCategoryForSitemap(categoryModel))
    .collect(Collectors.toList());

You can't just cast stream to something.

If you want to get result you have to call one of terminal operation. In this case you need collect.

Upvotes: 1

WJS
WJS

Reputation: 40057

One problem is that you need to put a collector on the stream to return a list. But there may be additional problems that aren't as obvious.

List<CategoryModel> sitemapList = categoryList.stream()
                .filter(categoryModel -> selectCategoryForSitemap(
                        categoryModel)).collect(Collectors.toList());

Upvotes: 1

Related Questions