Muh*_*edy 5 collections guava java-7 java-8 apache-commons-collection
我喜欢的意思intermediate operations是Java8,当a terminal operation到达时,所有操作都会应用一次.
我在问是否有我可以使用的库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()方法实际上并不进行转换,而是返回一个特制的类,它只在需要时计算值.
奖金证明它一切都很好用:如果我们删除了空循环并用例如just替换它integers.get(1);,它实际上只会输出数字2.
如果你想将多种方法连在一起,总会有FluentIterable.这基本上允许您使用类似Java 8 Stream的样式进行编码.
虽然Guava通常默认使用正确的东西并且与JDK类一起使用,但有时候你需要更复杂的东西.这就是Goldman Sachs系列的用武之地.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
}
突然输出一切.
| 归档时间: | 
 | 
| 查看次数: | 234 次 | 
| 最近记录: |