Java7中的集合中间操作库

Muh*_*edy 5 collections guava java-7 java-8 apache-commons-collection

我喜欢的意思intermediate operationsJava8,当a terminal operation到达时,所有操作都会应用一次.

我在问是否有我可以使用的库Java 7允许我实现这样的行为.

注意:
commons-collections4用于收集操作,比如forAllDo,所以有可能在这种情况下使用它吗?(中间与终端运营)

Pet*_*ček 9

番石榴

正如您的[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);
    }
});
Run Code Online (Sandbox Code Playgroud)

这段代码似乎将a转换List<String>List<Integer>while也将字符串写入输出.但如果你真的运行它,它什么都不做.我们再添加一些代码:

for (Integer i : integers) {
    // nothing to do
}
Run Code Online (Sandbox Code Playgroud)

现在它将输入写出来!

那是因为该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);
    }
});
Run Code Online (Sandbox Code Playgroud)

再说一遍,什么都不做.但:

for (Integer i : integers) {
    // nothing to do
}
Run Code Online (Sandbox Code Playgroud)

突然输出一切.

  • PS在现实世界中,如果我必须将`List <String>`转换为`List <Integer>`,我会使用[`Ints.stringConverter()`](http://docs.guava- libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Ints.html#stringConverter%28%29)作为转换函数. (4认同)