Reputation: 921
Here is my parent class
class Parent
{
String attrib1;
String attrib2;
String attrib3;
// getters and setters of three fields
Then I created a list
List<Parent> objList = new ArrayList<Parent>();
Then I added a number of Parent objects to objList.
Now I want to filter these objects based on value of the fields in the class. But I will get field name only dynamically. I want to use streams for this purpose.
List<Parent> temp = objList.stream()
.filter(nestedDo -> nestedDo.getAttrib2() == "manu")
.collect(Collectors.toList());
Here getAttrib2() varies. It can be getAttrib1() or getAttrib3().
So I need dynamic function calling. Can we achieve it using Predicates. Unfortunately, I don't know anything about the Predicate object. Please explain your answer elaborately with all concepts inside it.
Upvotes: 1
Views: 1953
Reputation: 21981
Yes, you can create different Predicate and use them based on condition.
Predicate<Parent> first= e -> e.getAttrib1().equals("nanu");
Predicate<Parent> second= e -> e.getAttrib2().equals("..");
List<Parent> temp = objList.stream()
.filter(first) // Similarly you can call second
.collect(Collectors.toList());
Upvotes: 2