java8 lambda表达式

允我心安 提交于 2019-11-27 13:28:38

参考博客:https://www.520mwx.com/view/44313

自己玩的代码:

Student实体类

public class Student {
        private String name;
        private int age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public Student() {
            super();
            // TODO Auto-generated constructor stub
        }
        public Student(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
        @Override
        public String toString() {
            return "Student [name=" + name + ", age=" + age + "]";
        }
        public void eat() {
            System.out.println("eat food...");
        }
        @Override
        public boolean equals(Object obj) {
            if(this == obj) {
                return true;
            }
            if(obj instanceof Student) {
                if(this.getAge() == ((Student)obj).getAge()) {
                    return true;
                }
            }
            return false;
        }
        @Override
        public int hashCode() {
            return getAge();
        }
}

Main:

public class TestMain {
    public static void main(String[] args) {
         List<Student> stus = new ArrayList<>();
         Student s1 = new Student();
         Student s2 = new Student();
         Student s3 = new Student();
         s1.setAge(12);
         s1.setName("zzj");
         s2.setAge(14);
         s2.setName("zzx");
         s3.setAge(13);
         s3.setName("zzk");
         stus.add(s1);stus.add(s2);stus.add(s3);
         stus.forEach(i->{
             Integer k = i.getAge()+1;
             System.out.println(k);
         });
         stus.stream().filter(i->!"zzkz".equals(i.getName())).sorted(Comparator.comparing(Student::getAge)).forEach(i->{
            System.out.println(i.getName() + " -- "+ i.getAge()); 
         });
 

    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!