有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中,当过滤器只返回一个对象时,如何使用流和过滤器将值填充到对象中

我有一个parentObject和一组ChildObject。这些子对象有不同的子名称。 因此,如果我使用childName筛选子对象,则只会返回一个对象。使用forEach填充值可以很好地工作,但在这种情况下不需要使用forEach,因为只返回一个子对象。 这是我目前的代码

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);
    });

下面显示了相同的子类

class Child(){

private String name;
private int age;

public Child(String name){
  this.name = name;
}

public String getName(){
  return this.name;
}

}

有人能解释一下如何在不使用forEach的情况下填充值吗


共 (0) 个答案