如何在 Java 中实现列表折叠 [英] How to implement a list fold in Java
问题描述
我有一个 List 并且想将它减少到单个值(函数式编程术语折叠",Ruby 术语 inject
),例如
I have a List and want to reduce it to a single value (functional programming term "fold", Ruby term inject
), like
Arrays.asList("a", "b", "c") ... fold ... "a,b,c"
由于我被函数式编程思想 (Scala) 所感染,我正在寻找一种比代码更简单/更短的方法
As I am infected with functional programming ideas (Scala), I am looking for an easier/shorter way to code it than
sb = new StringBuilder
for ... {
append ...
}
sb.toString
推荐答案
您正在寻找的是一个字符串 join()
方法,Java 从 8.0 开始就有.尝试以下方法之一.
What you are looking for is a string join()
method which Java has since 8.0. Try one of the methods below.
Collection<String> source = Arrays.asList("a", "b", "c");
String result = String.join(",", source);
Stream interface supports a fold operation very similar to Scala’s foldLeft
function. Take a look at the following concatenating Collector:
Collection<String> source = Arrays.asList("a", "b", "c");
String result = source.stream().collect(Collectors.joining(","));
您可能希望静态导入 Collectors.joining
以使您的代码更清晰.
You may want to statically import Collectors.joining
to make your code clearer.
顺便说一下,这个收集器可以应用于任何特定对象的集合:
By the way this collector can be applied to collections of any particular objects:
Collection<Integer> numbers = Arrays.asList(1, 2, 3);
String result = numbers.stream()
.map(Object::toString)
.collect(Collectors.joining(","));
这篇关于如何在 Java 中实现列表折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!