java8 lambda表达式

参考博客: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()); 
         });
 

    }
}

 

posted on 2019-08-16 18:34  Esquecer  阅读(188)  评论(0编辑  收藏  举报

导航