Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Uses of Java 8 predicates in android to filter data

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 573
    Comment on it

    Predicates basically used in ios to query over model class data but from java 8 its available in android or java this function returns true or false value based on condition like P: Y? {true, false} that predicates on.

    Example : We have a model class named Employee for age and salary

    public class Employee {
        public Class(Integer salary, Integer age){
            msalary = salary;
            mage = age;
        }
        private Integer msalary;
        private Integer mage;
        public Integer getmsalary() {
            return msalary;
        }
        public void setmsalary(Integer msalary) {
            this.msalary = msalary;
        }
        public Integer getmage() {
            return mage;
        }
        public void setmage(Integer mage) {
            this.mage = mage;
        }
        @Override
        public String toString() {
            return this.msalary.toString()+" - "+this.mage.toString();
        }
    }

    Now We can create Predicates like this :

    public class EmployeePredicates
    {
        public static Predicate<Employee> isAgeMoreThan(Integer age) {
            return p -> p.getAge() > age;
        }
        public static List<Employee> filterEmployee (List<Employee> employee, Predicate<Employee> predicate) {
            return employee.stream().filter( predicate ).collect(Collectors.<Employee>toList());
        }
    }

    This function will check and return new collection list that will satisfy predicates conditions like this.

    Main class to pass students objects like this :

    public class TestingPredicates {
        public static void main(String[] args){
            Employee e1 = new Employee(11234,23);
            Employee e2 = new Employee(212312,13);
            Employee e3 = new Employee(31231,43);
            List<Employee> employee = new ArrayList<Employee>();
            employee.addAll(Arrays.asList(new Employee[]{e1, e2, e3}));
            System.out.println(filterEmployee(employee, 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: