I have a parentObject with collection of childObjects. These childObjects have distinct child names. So if I filter the child objects with childName, only one object would be returned. Populating values using forEach works fine,but there is no need to use forEach in this case as only one child object is returned. This is my current code.
Child childOne = new Child("ken");
Child childTwo = new Child("mathew");
Collection<Child> collectionOfChildObjects = new ArrayList<>();
collectionOfChildObjects.add(childOne);
collectionOfChildObjects.add(childTwo);
parentObject.setCollectionOfChildObjects(collectionOfChildObjects);
String value="ken";
parentObject.getCollectionOfChildObjects().stream()
.filter(childObject-> Objects.equals(
value,
childObject.getChildName()))
.forEach(childObj-> {
childObj.setAge(5);
});
The Child class for the same is shown below.
class Child(){
private String name;
private int age;
public Child(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
Can someone please explain how to populate values without the use of forEach.