Java8之Predicate接口使用

优点:过滤条件可以不用写对应的if else条件

public static void main(String[] args) {
        List<MessageRecord> messageRecords = Lists.newArrayList();
        for (int i = 0; i < 2; i++) {
            MessageRecord messageRecord = new MessageRecord();
            messageRecord.setSourceSystemId("biz-rcs-cmc-demo");
            Map<String, Object> map = new HashMap<>();
            map.put(MessagePropertyNames.RETRY_ORIGIN_MSGID, i);
            messageRecord.setProperties(map);
            messageRecords.add(messageRecord);
        }
        for (int i = 0; i < 2; i++) {
            MessageRecord messageRecord = new MessageRecord();
            messageRecord.setSourceSystemId("biz-rcs-cmc");
            messageRecords.add(messageRecord);
        }
        for (int i = 0; i < 2; i++) {
            MessageRecord messageRecord = new MessageRecord();
            messageRecord.setSourceSystemId("biz-rcs-cmc-test");
            messageRecords.add(messageRecord);
        }
        List<MessageRecord> messageRecordList = conditionOrFilter(messageRecords, messageRecord -> "biz-rcs-cmc".equals(messageRecord.getSourceSystemId()), messageRecord -> {
            Integer retryOriginMsgId = messageRecord.getProperty(MessagePropertyNames.RETRY_ORIGIN_MSGID);
            return !ObjectUtils.isEmpty(retryOriginMsgId);
        });
        messageRecordList.forEach(messageRecord -> {
            log.info("sourceSystemId:{}, _retryOriginMsgId:{}", messageRecord.getSourceSystemId(), messageRecord.getProperty(MessagePropertyNames.RETRY_ORIGIN_MSGID));
        });
    }

    /**
     * 过滤条件或的关系
     * @param list
     * @param predicate
     * @param predicateTemp
     * @return
     */
    public static List<MessageRecord> conditionOrFilter(List<MessageRecord> list, Predicate<MessageRecord> predicate, Predicate<MessageRecord> predicateTemp){
        return list.stream().filter(predicate.or(predicateTemp)).collect(Collectors.toList());
    }

    /**
     * 过滤条件与的关系
     * @param list
     * @param predicate
     * @param predicateTemp
     * @return
     */
    public static List<MessageRecord> conditionAndFilter(List<MessageRecord> list, Predicate<MessageRecord> predicate, Predicate<MessageRecord> predicateTemp){
        return list.stream().filter(predicate.and(predicateTemp)).collect(Collectors.toList());
    }
    
    /**
     * 过滤单个条件
     * @param list
     * @param predicate
     * @return
     */
    public static List<MessageRecord> conditionFilter(List<MessageRecord> list, Predicate<MessageRecord> predicate){
        return list.stream().filter(predicate).collect(Collectors.toList());
    }

  

posted @ 2021-07-15 14:16  A小小高  阅读(645)  评论(0编辑  收藏  举报