利用Stream改变list中特定对象的某一属性

list.stream() .filter(dog -> dog.getAge()<50)  .forEach(dog -> dog.setAge(26));

利用Stream改变list中特定对象的某一属性_第1张图片

import java.util.ArrayList;
import java.util.List;
public class StreamTest {
    public static void main(String[] args) {
        Dog dog1=new Dog("旺财",13);
        Dog dog2=new Dog("旺财",45);
        Dog dog3=new Dog("旺财",60);
        List<Dog> list=new ArrayList<>();
        list.add(dog1);
        list.add(dog2);
        list.add(dog3);

        list.stream() .filter(dog -> dog.getAge()<50)  .forEach(dog -> dog.setAge(26));


        System.out.println(list);
    }
}

class Dog{
    private String name;
    private Integer age;

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

你可能感兴趣的:(java基础,list,java,数据结构)