Published 15 Oct, 2022

Java - Filter a list with streams based on ids from another list

Category Java
Modified : Nov 30, 2022

I have a list of Product objects with 30 objects.

I have created a fix list with strings of ids.

List<String> productsIdsForFreeSchoolYear = Arrays.asList("169", "172", "198", "213", "358", "4529", "6602", "5958");

What I want to do is to get list of Product only contains the ids from productsIdsForFreeSchoolYear list.

This is what i tried, but its seems its only check if the ids exists? Im i right?

productsSelectable is the list of Product.

Thank you!


There are 1 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Java 8, Java Stream. These have been categorized in sections for a clear and precise explanation.


In your code, contains() will always return false because it's a list of IDs (strings), and you're passing it a Product instance. You probably want something like this:
            .filter(p -> productsIdsForFreeSchoolYear.contains(p.getId()))