gpt4 book ai didi

java - Guava - 如何应用在 Iterable 上返回 Void 的函数

转载 作者:搜寻专家 更新时间:2023-10-30 19:49:21 25 4
gpt4 key购买 nike

我只是想知道应用返回 Void 的函数的最佳方法是什么在 Iterable/Collection 上?

我的用例是:

  • 我有一个 Animal 的列表对象
  • 我想调用列表中的每只动物 eat()功能

我有一个 Function<Animal,Void>这叫input.eat();

事实证明,当我打电话时:

Collections2.transform(animalList,eatFunction);

我觉得这不是很优雅,因为我不是在寻找转换,而是仅针对没有任何输出的应用程序。最糟糕的是,它甚至不起作用,因为 Guava 转换正在返回 View 。

有效的是:

Lists.newArrayList( Collections2.transform(animalList,eatFunction) );

但这并不优雅。使用 Guava 以函数式方式将 Void 函数应用于 Iterable/Collection 的最佳方法是什么?

编辑:

最佳答案

你觉得什么比较优雅?一个普通的 for 循环:

for (Animal animal : animalList)
animal.eat();

还是“通过以函数式风格编写过程操作来改变过程语言”的疯狂行为?

static final Function<Animal, Void> eatFunction = new Function<Animal, Void>() {
@Override
public Void apply(Animal animal) {
animal.eat();
return null; // ugly as hell, but necessary to compile
}
}

Lists.newArrayList(Collections2.transform(animalList, eatFunction));

我会投票给第一种情况。

如果您真的想用函数式风格编写程序,我建议您切换到另一种 JVM 语言。

Scala 可能是这种情况的一个很好的选择:

animalList.foreach(animal => animal.eat)

甚至使用 _ 占位符的更短变体:

animalList.foreach(_.eat)

编辑:

在 Eclipse 中尝试代码后,我发现我必须将 return null 语句添加到 eatFunction,因为 1) Voidvoid 不同,并且 2) 它是不可实例化的。这比预期的还要丑陋! :)

同样从性能的角度来看,像上面这样使用一些复制构造函数调用惰性函数也会毫无意义地分配内存。创建一个与仅填充空值的 animalList 大小相同的 ArrayList,以便立即进行垃圾回收。

如果你真的有一个用例,你想传递一些函数对象并将它们动态地应用到一些集合上,我会写我自己的函数接口(interface)和一个 foreach 方法:

public interface Block<T> {
void apply(T input);
}

public class FunctionUtils {
public static <T> void forEach(Iterable<? extends T> iterable,
Block<? super T> block) {
for (T element : iterable) {
block.apply(element);
}
}

}

然后你可以类似地定义一个void(小写)函数:

static final Block<Animal> eatFunction = new Block<Animal>() {
@Override
public void apply(Animal animal) {
animal.eat();
}
};

然后像这样使用它:

FunctionUtils.forEach(animalList, eatFunction);
// or with a static import:
forEach(animalList, eatFunction);

关于java - Guava - 如何应用在 Iterable 上返回 Void 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426803/

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