如何在Java中实现列表折叠 [英] How to implement a list fold in Java

查看:319
本文介绍了如何在Java中实现列表折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,并希望将其减少为单个值(函数式编程术语fold,Ruby术语 inject ),如

  Arrays.asList(a,b,c)... fold ...a,b,c

当我感染了函数式编程思想(Scala)时,我正在寻找一种更简单的方法来编写它

  sb = new StringBuilder 
for ... {
append ...
}
sb.toString


解决方案

寻找是一个字符串 join()方法,Java自8.0以来。请尝试以下方法之一。


  1. 静态方法 String#join(delimiter,elements)

     集合< String& source = Arrays.asList(a,b,c); 
    String result = String.join(,,source);


  2. Stream 接口支持与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.

  1. Static method String#join(delimiter, elements):

    Collection<String> source = Arrays.asList("a", "b", "c");
    String result = String.join(",", source);
    

  2. 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中实现列表折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆