Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use predicates in android or java 8 ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.45k
    Comment on it

    Do you have lots of data of an employee and you want to filter it without using database query then you can use predicates that also provides you queries on beans or model class.

    Basically predicates comes from predicate function that returns true or false value based on condition like P: Y? {true, false} that predicates on X.

    Example : We have a model class named Students for age and id of students

    public class Students {
    
        public Class(Integer id, Integer age){
            mId = id;
            mAge = age;
    
        }
    
        private Integer mId;
        private Integer mAge;
    
        public Integer getmId() {
            return mId;
        }
    
        public void setmId(Integer mId) {
            this.mId = mId;
        }
    
        public Integer getmAge() {
            return mAge;
        }
    
        public void setmAge(Integer mAge) {
            this.mAge = mAge;
        }
    
        @Override
        public String toString() {
            return this.mId.toString()+" - "+this.mAge.toString();
        }
    }
    

     

    Now We can create Predicates like this :

    public class StudentsPredicates
    {
    
        public static Predicate<Students> isAgeMoreThan(Integer age) {
            return p -> p.getAge() > age;
        }
    
        public static List<Students> filterStudents (List<Students> students, Predicate<Students> predicate) {
            return students.stream().filter( predicate ).collect(Collectors.<Students>toList());
        }
    }

    so we have filter function where we will pass students types of list and predicates on this, then this function will return new collection of list satisfying predicate condition.

    Main class to pass students objects like this :

    public class TestPredicates {
        public static void main(String[] args){
            Student s1 = new Student(1,23);
            Student s2 = new Student(2,13);
            Student s3 = new Student(3,43);
    
    
            List<Student> students = new ArrayList<Student>();
            students.addAll(Arrays.asList(new Student[]{e1, e2, e3}));
    
            System.out.println(filterStudents(students, isAgeMoreThan(35)));
        }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: