gpt4 book ai didi

java - Iterators.filter 与 for-each

转载 作者:行者123 更新时间:2023-11-30 03:49:04 24 4
gpt4 key购买 nike

也许这是一个显而易见或愚蠢的问题,所以我提前表示歉意。

假设我有以下两种使用简单条件迭代集合的方法:

1

Predicate<SomeObject> pred1 = new Predicate<SomeObject> () {... some condition_1 ...};
Predicate<SomeObject> pred2 = new Predicate<SomeObject> () {... some condition_2 ...};
Iterator<SomeObject> newIterator = Iterators.filter(iterator, pred1);
... do something like Sets.newHashSet(newIterator) ...
newIterator = Iterators.filter(iterator, pred2);
... do something like Sets.newHashSet(newIterator) ...

2

while(iterator.hasNext()) {
SomeObject someObject = iterator.next();
if (condition_1) {
...do something like set.add(someObject)...
} else if (condition_2) {
...do something like set.add(someObject)...
}
}

我说得对吗,#2 比 #1 更快?

感谢您的回答!

最佳答案

命令式版本会更快,但是快多少很难确定。在我的测试中,一旦热了,两个版本都会在 1.1 微秒内返回。命令式版本方法在 95% 的情况下运行速度超过 5.15 微秒(随机执行运行 1,000,000 次),而 FluentIterable 版本在 95% 的情况下运行速度超过 6.6 微秒。

Guava 可以非常快,特别是如果可以静态定义谓词和函数。

在下面的示例中,请注意谓词组合和 FluentIterable 的用法。

FluentIterable 特别有吸引力,因为只需进行最少的修改即可用 Java 8 流替换用法。

public static class SomeObject {

private final String someString;

public SomeObject(final String someString) {
this.someString = someString;
}

public String getSomeString() {
return this.someString;
}

@Override
public String toString() {
return this.someString;
}
}

public static final Predicate<SomeObject> CONTAINS_A_FILTER = new Predicate<GuavaExample.SomeObject>() {

@Override
public boolean apply(final SomeObject someObject) {

return someObject.getSomeString()
.contains("A");
}
};

public static final Predicate<SomeObject> CONTAINS_B_FILTER = new Predicate<GuavaExample.SomeObject>() {

@Override
public boolean apply(final SomeObject someObject) {

return someObject.getSomeString()
.contains("B");
}
};

public static final Predicate<SomeObject> CONTAINS_A_AND_B_FILTER = Predicates.and(CONTAINS_A_FILTER,
CONTAINS_B_FILTER);

public static final Predicate<SomeObject> CONTAINS_A_OR_B_FILTER = Predicates.or(CONTAINS_A_FILTER,
CONTAINS_B_FILTER);

public static void main(final String... args) {

final List<SomeObject> someObjects = ImmutableList.of(new SomeObject("A"), new SomeObject("AB"),
new SomeObject("B"), new SomeObject("C"));

final Set<SomeObject> containsAandB = FluentIterable.from(someObjects)
.filter(CONTAINS_A_AND_B_FILTER)
.toSet();

// prints [AB]
System.out.println(containsAandB);

final Set<SomeObject> containsAOrB = FluentIterable.from(someObjects)
.filter(CONTAINS_A_OR_B_FILTER)
.toSet();

// prints [A, AB, B]
System.out.println(containsAOrB);
}

关于java - Iterators.filter 与 for-each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com