intermediate operations
我喜欢 of的想法Java8
,当terminal operation
达到 a 时,所有操作都将应用一次。
我在问是否有可以使用的库Java 7
来实现这种行为。
注意:
我commons-collections4
用于收集操作,例如forAllDo,所以可以将它用于这种情况吗?(中间与终端操作)
intermediate operations
我喜欢 of的想法Java8
,当terminal operation
达到 a 时,所有操作都将应用一次。
我在问是否有可以使用的库Java 7
来实现这种行为。
注意:
我commons-collections4
用于收集操作,例如forAllDo,所以可以将它用于这种情况吗?(中间与终端操作)
正如您的 [Guava] 标签所暗示的,大多数 Guava 收集操作都是惰性的 - 它们仅在需要时应用。例如:
List<String> strings = Lists.newArrayList("1", "2", "3");
List<Integer> integers = Lists.transform(strings, new Function<String, Integer>() {
@Override
public Integer apply(String input) {
System.out.println(input);
return Integer.valueOf(input);
}
});
此代码似乎将 a 转换List<String>
为List<Integer>
while 还将字符串写入输出。但如果你真的运行它,它什么也做不了。让我们添加更多代码:
for (Integer i : integers) {
// nothing to do
}
现在它把输入写出来!
这是因为该Lists.transform()
方法实际上并不进行转换,而是返回一个特制的类,该类仅在需要时计算值。
额外证明这一切都很好:如果我们删除空循环并将其替换为 eg just integers.get(1);
,它实际上只会输出 number 2
。
如果您想将多个方法链接在一起,总是有FluentIterable
. 这基本上允许您以 Java 8 Stream-like 风格进行编码。
虽然 Guava 通常默认情况下会做正确的事情并与 JDK 类一起使用,但有时您需要更复杂的东西。这就是高盛收藏品的用武之地。GS 收藏品拥有一个完整的即插即用的收藏品框架,包含您梦寐以求的一切,为您提供了更大的灵活性和强大的功能。惰性默认情况下不存在,但可以轻松实现:
FastList<String> strings = FastList.newListWith("1", "2", "3");
LazyIterable<Integer> integers = strings.asLazy().collect(new Function<String, Integer>() {
@Override
public Integer valueOf(String string) {
System.out.println(string);
return Integer.valueOf(string);
}
});
再次,什么都不做。但:
for (Integer i : integers) {
// nothing to do
}
突然输出一切。