Java code of the United States (13) --- Predicate Detailed

Java code of the United States (13) --- Predicate Detailed

Encounter Predicatetheir own in the Custom Mybatis interceptors when we are in the interceptor through the reflection of all property acquired objects, and then see if we have these attributes UUID custom annotations .

If the annotation, then give the UUID attribute assignment random string stored in the database as the primary key. So prerequisite is to get the UUID attribute with annotations, you need to use Predicate.

//获取所有带UUID注解的属性
 Set<Field> allFields = ReflectionUtils.getFields(object.getClass(),x.getAnnotation(UUId.class) != null);

Also think of their own before when dealing with a collection of steam, but also with the filters you've added Predicate, but they are not under the same package. Although they are not under the same package but their effect is the same, that is,

Predicate接口主要用来判断一个参数是否符合要求

The following are the two interfaces will be described and exemplified.

一、java.util.function.Predicate

Here comes the main java class is widely used in support lambda expressions API.

1, the interface source code

@FunctionalInterface
public interface Predicate<T> {
    /**
     * 具体过滤操作 需要被子类实现.
     * 用来处理参数T是否满足要求,可以理解为 条件A
     */
    boolean test(T t);
    /**
     * 调用当前Predicate的test方法之后再去调用other的test方法,相当于进行两次判断
     * 可理解为 条件A && 条件B
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    /**
     * 对当前判断进行"!"操作,即取非操作,可理解为 ! 条件A
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }
    /**
     * 对当前判断进行"||"操作,即取或操作,可以理解为 条件A ||条件B
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * 对当前操作进行"="操作,即取等操作,可以理解为 A == B
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

2, the conventional example

    public static void main(String[] args) {
        /**
         * 1、判断数字是否大于7
         */
        //设置一个大于7的过滤条件
        Predicate<Integer> predicate = x -> x > 7;
        System.out.println(predicate.test(10)); //输出 true
        System.out.println(predicate.test(6));  //输出 fasle
         /**
          * 2、大于7并且
          */
        //在上面大于7的条件下,添加是偶数的条件
        predicate = predicate.and(x -> x % 2 == 0);
        System.out.println(predicate.test(6));  //输出 fasle
        System.out.println(predicate.test(12)); //输出 true
        System.out.println(predicate.test(13)); //输出 fasle
        /**
         * 3、add or 简化写法
         */
        predicate = x -> x > 5 && x < 9;
        System.out.println(predicate.test(10)); //输出 false
        System.out.println(predicate.test(6));  //输出 true
    }

3, an example set of Stream

User objects

@Data
@AllArgsConstructor
@ToString
public class User {
    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String sex;

    /**
     * 年龄
     */
    private Integer age;
    
   /**
     * 重写equals和hashCode
     */
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof User) {
            User user = (User) obj;
            if (name.equals(user.name)){
                return true;
            }
        }
            return false;
        }
        @Override
        public int hashCode () {
            return name.hashCode();
        }

    }

Test code

    public static void main(String[] args) {
        User user1 = new User("张三", "女", 1);
        User user2 = new User("李四", "男", 2);
        User user3 = new User("张三", "女", 3);
        List<User> list = Lists.newArrayList(user1, user2, user3);

       /**
        * 1、获取年龄大于2的对象
        */
        List<User> collect = list.stream().filter(x -> x.getAge() > 2).collect(Collectors.toList());
        System.out.println("获取年龄大于2的数量 = " + collect.size());
        //输出:获取年龄大于2的数量 = 1

        /**
         * 2、去重 设置name相同即为相同对象
         */
        //方式1直接使用 distinct
        List<User> collect1 = list.stream().distinct().collect(Collectors.toList());
        System.out.println("输出剩余对象" + collect1);
        //输出:输出剩余对象[User(name=张三, sex=女, age=1), User(name=李四, sex=男, age=2)]

        /**
         * 3、从集合找出与该对象相同的元素 同样name相同即为相同对象
         */
        User user4 = new User("张三", "男", 8);
        Predicate<User> predicate =  Predicate.isEqual(user4);
        List<User> collect2 = list.stream().filter(predicate).collect(Collectors.toList());
        System.out.println("与该对象相同的对象有" + collect2);
        //输出:与该对象相同的对象有[User(name=张三, sex=女, age=1), User(name=张三, sex=女, age=3)]
    }

operation result


二、com.google.common.base.Predicate

Predicate here is with guava use.

作用

  1. Processing the set of filter conditions
  2. Conditioning tools of the filter

If as a filter collection, it is now no need to use it, because JDK1.8 when dealing with a collection of stream than it easy to use more.

1, the interface source code

@GwtCompatible
public interface Predicate<T> {
  //重写过滤条件
  @CanIgnoreReturnValue
  boolean apply(@Nullable T input);
  //重写equals
  boolean equals(@Nullable Object object);

When using two methods you need to rewrite it.

2, Example

Custom UUID comment

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface UUID {
}

Person

@Data
@AllArgsConstructor
@ToString
public class Person {
    /**
     * 姓名 在name上使用UUID注解
     */
    @UUID
    private String name;
    /**
     * 性别
     */
    private String sex;
    /**
     * 年龄
     */
    private Integer age;
}

Test code

 public static void main(String[] args) {
        Person person1 = new Person("张三", "女", 1);
        Person person2 = new Person("李四", "男", 2);
        Person person3 = new Person("张三", "女", 3);

        List<Person> list = Lists.newArrayList(person1, person2, person3);
        /**
         * 1、guava使用过滤 年龄大于2的
         */
        Predicate<Person> predicate1 = new Predicate<Person>() {
            //重写两个方法
            @Override
            public boolean apply(Person input) {
                if (input.getAge() > 2) {
                    return true;
                }
                return false;
            }
            @Override
            public boolean equals(Object object) {
                return true;
            }
        };
        list = Lists.newArrayList(Iterables.filter(list,predicate1));
        System.out.println("过滤后的集合数据: "+list);
        //输出: 过滤后的集合数据: [Person(name=张三, sex=女, age=3)]

        /**
         * 2、配合反射工具类ReflectionUtils过滤获取属性
         */
        Person person4 = new Person("张三", "女", 1);
        Set<Field> allFields = org.reflections.ReflectionUtils.getFields(person4.getClass(),x -> x != null && x.getAnnotation(UUID.class) != null);
        System.out.println("带UUID注解的属性有 "+ allFields);
        //输出 :带UUID注解的属性有 [private java.lang.String com.jincou.vo.Person.name]
    }

operation result

Obviously, there has to acquire the property is annotated with a UUID name.




只要自己变优秀了,其他的事情才会跟着好起来(上将12)

Guess you like

Origin www.cnblogs.com/qdhxhz/p/11323595.html