簡體   English   中英

Java 6 guava謂詞到Java 8謂詞和Lambda

[英]Java 6 guava Predicate to Java 8 Predicate & Lambda

我一直在使用Java 6進行開發並使用guava謂詞。 但是我想切換到Java 8並改用Java util謂詞。 我可以簡單地將以下方法轉換為使用謂詞,但是有沒有使用Lambda表達式並減少代碼行數的聰明方法? 最好刪除我要創建的臨時列表? 我正在搜索示例,但所有示例都是非常簡單的示例。 感謝您的幫助!

    private Predicate<Objt1> getLocalAttributesPredicate() {
    return new Predicate<Objt1>() {

        @Override
        public boolean apply(Objt1 input) {

            AttributeType attr = cache.get(input.getAttributeID());
            List<String> attrGroupids = Lists.newArrayList();
            for (AttributeGroupLinkType group : attr.getAttributeGroupLink()) {
                attrGroupids.add(group.getAttributeGroupID());
            }
            return attrGroupids.contains(localAttrGroupId) && !attrGroupids.contains(exclustionAttrGroupId);
        }
    };
}

類似於以下內容:

private Predicate<Objt1> getLocalAttributesPredicate() {
    return input -> cache.get(input.getAttributeID())
            .stream()
            .map(group -> group.getAttributeGroupID())
            .filter(id -> id.equals(localAttrGroupId))
            .filter(id -> !id.equals(exclustionAttrGroupId))
            .limit(1)
            .count() > 0;
}

因此,謂詞作為lambda函數返回,並且它利用Stream API遍歷列表並轉換其內容。

編輯:應用了@Aominè建議的優化,謝謝。

從Java-8開始,這是您的處理方式:

private Predicate<Objt1> getLocalAttributesPredicate() {
   return input ->  { 
         Set<String> accumulator = ...
         AttributeType attr = cache.get(input.getAttributeID());
         for(AttributeGroupLinkType group : attr.getAttributeGroupLink())
              accumulator.add(group.getAttributeGroupID());
         return accumulator.contains(localAttrGroupId) &&
                !accumulator.contains(exclustionAttrGroupId);
   };
}

請注意,我還使用了Set作為累加器,因為Set實現的Contains方法比List實現快得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM