Java 6 番石榴谓词到 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);
}
};
}
从 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
,因为 Contains
方法对于 Set
实现比对于 List
实现要快得多.
类似于以下内容:
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 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);
}
};
}
从 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
,因为 Contains
方法对于 Set
实现比对于 List
实现要快得多.
类似于以下内容:
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è 建议的优化,谢谢。