问题描述
我有一个列表,并希望将其减少为单个值(函数式编程术语fold,Ruby术语 inject
),如
Arrays.asList(a,b,c)... fold ...a,b,c
当我感染了函数式编程思想(Scala)时,我正在寻找一种更简单的方法来编写它
sb = new StringBuilder
for ... {
append ...
}
sb.toString
寻找是一个字符串 join()
方法,Java自8.0以来。请尝试以下方法之一。
-
静态方法:
集合< String& source = Arrays.asList(a,b,c);
String result = String.join(,,source);
-
接口支持与Scala的
foldLeft
函数非常相似的折叠操作。请查看以下连结收集器:集合< String> source = Arrays.asList(a,b,c);
String result = source.stream()。collect(Collectors.joining(,));
您可能希望静态导入
Collectors.joining
$ b pre>Collection< Integer> numbers = Arrays.asList(1,2,3);
String result = numbers.stream()
.map(Object :: toString)
.collect(Collectors.joining(,));
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"
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
What you are looking for is a string join()
method which Java has since 8.0. Try one of the methods below.
Static method
String#join(delimiter, elements)
: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(","));
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中实现列表折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!