我有一个列表,想将其减少为单个值(函数式编程术语“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):

    Collection<String> source = Arrays.asList("a", "b", "c");
    String result = String.join(",", source);
    
  2. 溪流 界面支持与 Scala 非常相似的折叠操作 foldLeft 功能。看看下面的串联 集电极:

    Collection<String> source = Arrays.asList("a", "b", "c");
    String result = source.stream().collect(Collectors.joining(","));
    

    您可能想要静态导入 Collectors.joining 使您的代码更清晰。

    顺便说一下,这个收集器可以应用于任何特定对象的集合:

    Collection<Integer> numbers = Arrays.asList(1, 2, 3);
    String result = numbers.stream()
            .map(Object::toString)
            .collect(Collectors.joining(","));
    

其他提示

要回答你原来的问题:

public static <A, B> A fold(F<A, F<B, A>> f, A z, Iterable<B> xs)
{ A p = z;
  for (B x : xs)
    p = f.f(p).f(x);
  return p; }

其中F是这样的:

public interface F<A, B> { public B f(A a); }

称为DFA建议,功能的Java 已经此实现,并且更

实施例1:

import fj.F;
import static fj.data.List.list;
import static fj.pre.Monoid.stringMonoid;
import static fj.Function.flip;
import static fj.Function.compose;

F<String, F<String, String>> sum = stringMonoid.sum();
String abc = list("a", "b", "c").foldLeft1(compose(sum, flip(sum).f(",")));

实施例2:

import static fj.data.List.list;
import static fj.pre.Monoid.stringMonoid;
...
String abc = stringMonoid.join(list("a", "b", "c"), ",");

实施例3:

import static fj.data.Stream.fromString;
import static fj.data.Stream.asString;
...
String abc = asString(fromString("abc").intersperse(','));

鉴于

public static <T,Y> Y fold(Collection<? extends T> list, Injector<T,Y> filter){
  for (T item : list){
    filter.accept(item);
  }
  return filter.getResult();
}

public interface Injector<T,Y>{
  public void accept(T item);
  public Y getResult();
}

然后使用只是看起来像

fold(myArray, new Injector<String,String>(){
  private StringBuilder sb = new StringBuilder();
  public void Accept(String item){ sb.append(item); }
  public String getResult() { return sb.toString(); }
}
);

如果您想将某些功能方面应用于普通的旧式 Java,而不切换语言 虽然你可以 拉姆达, 分叉连接 (166y)谷歌收藏 是帮助您添加语法糖的库。

在...的帮助下 谷歌收藏 你可以使用 细木工班:

Joiner.on(",").join("a", "b", "c")

Joiner.on(",") 是一个不可变的对象,因此您可以自由共享它(例如作为常量)。

您还可以配置空处理,例如 Joiner.on(", ").useForNull("nil"); 或者 Joiner.on(", ").skipNulls().

为了避免在生成大字符串时分配大字符串,您可以使用它附加到现有的 Streams、StringBuilders 等。通过 Appendable 接口或 StringBuilder 班级:

Joiner.on(",").appendTo(someOutputStream, "a", "b", "c");

编写映射时,您需要两个不同的分隔符来用于条目以及键+值之间的分隔:

Joiner.on(", ").withKeyValueSeparator(":")
            .join(ImmutableMap.of(
            "today", "monday"
            , "tomorrow", "tuesday"))

你所寻找的是一个字符串“加入”功能,不幸的是,Java没有。你将不得不推出自己的加入功能,不应该是太辛苦了。

修改 org.apache.commons.lang.StringUtils 似乎具有许多有用的字符串功能(包括加入)。

不幸的是,在 Java 中你无法逃脱这个循环,但是有几个库。例如。你可以尝试几个库:

首先,您需要一个Java的功能库,提供通用的仿函数和功能的投影像倍。我设计并在这里实现了强大的(由于),但简单的这样的库: HTTP: //www.codeproject.com/KB/java/FunctionalJava.aspx (我发现其他库提到过于复杂)。

那么你的解决办法是这样的:

Seq.of("","a",null,"b","",null,"c","").foldl(
    new StringBuilder(), //seed accumulator
    new Func2<StringBuilder,String,StringBuilder>(){
        public StringBuilder call(StringBuilder acc,String elmt) {
            if(acc.length() == 0) return acc.append(elmt); //do not prepend "," to beginning
            else if(elmt == null || elmt.equals("")) return acc; //skip empty elements
            else return acc.append(",").append(elmt);
        }
    }
).toString(); //"a,b,c"

请注意,通过应用倍,即真正需要深思熟虑的唯一部分是用于Func2.call实施,代码3行限定的操作者接受累加器和元素并返回所述蓄能器(我的实现占空字符串和空值,如果删除该情况下那么它下降到2行的代码)。

和这里的Seq.foldl的实际执行中,SEQ实现了Iterable

public <R> R foldl(R seed, final Func2<? super R,? super E,? extends R> binop)
{
    if(binop == null)
        throw new NullPointerException("binop is null");

    if(this == EMPTY)
        return seed;

    for(E item : this)
        seed = binop.call(seed, item);

    return seed;
}

GS类别具有injectInto(如红宝石),makeString和appendString。下面将你的榜样工作:

String result1 = FastList.newListWith("a", "b", "c").makeString(",");
StringBuilder sb = new StringBuilder();
FastList.newListWith("a", "b", "c").appendString(sb, ",");
String result2 = sb.toString();
Assert.assertEquals("a,b,c", result1); 
Assert.assertEquals(result1, result2);

注意:我在GS类别的显影剂

不幸的是,Java 不是一种函数式编程语言,并且没有一个好的方法来完成您想要的事情。

我相信 Apache Commons lib 有一个 称为连接的函数 但这会做你想做的事。

它必须足够好才能隐藏方法中的循环。

public static String combine(List<String> list, String separator){
    StringBuilder ret = new StringBuilder();
    for(int i = 0; i < list.size(); i++){
        ret.append(list.get(i));
        if(i != list.size() - 1)
            ret.append(separator);
    }
    return ret.toString();
}

我想你可以递归地做到这一点:

public static String combine(List<String> list, String separator){
    return recursiveCombine("", list, 0, separator);
}

public static String recursiveCombine(String firstPart, List<String> list, int posInList, String separator){
    if (posInList == list.size() - 1) return firstPart + list.get(posInList);

    return recursiveCombine(firstPart + list.get(posInList) + separator, list, posInList + 1, seperator);
}

现在你可以使用String.join()与Java 8。

    List strings = Arrays.asList("a", "b", "c");
    String joined = String.join(",", strings);
    System.out.println(joined);

通过支撑lambda表达式,我们可以用下面的代码做:

static <T, R> R foldL(BiFunction<R, T, R> lambda, R zero, List<T> theList){

     if(theList.size() == 0){
      return zero;
     }

     R nextZero = lambda.apply(zero,theList.get(0));

     return foldL(lambda, nextZero, theList.subList(1, theList.size()));                  
    }

下面是代码由背部保持节点的信息让后面和折叠因为我们向前迈进列表折叠。

public class FoldList {
    public static void main(String[] args) {
        Node a = new Node(1);
        Node b = new Node(2);
        Node c = new Node(3);
        Node d = new Node(4);
        Node e = new Node(5);
        Node f = new Node(6);
        Node g = new Node(7);
        Node h = new Node(8);
        Node i = new Node(9);
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;
        e.next = f;
        f.next = g;
        g.next = h;
        h.next = i;

        foldLinkedList(a);

    }

    private static void foldLinkedList(Node a) {
        Node middle = getMiddleNodeOfTheList(a);
        reverseListOnWards(middle);
        foldTheList(a, middle);

    }

    private static Node foldTheList(Node a, Node middle) {
        Node leftBackTracePtr = a;
        Node leftForwardptr = null;
        Node rightBackTrack = middle;
        Node rightForwardptr = null;
        Node leftCurrent = a;
        Node rightCurrent = middle.next;
        while (middle.next != null) {
            leftForwardptr = leftCurrent.next;
            rightForwardptr = rightCurrent.next;
            leftBackTracePtr.next = rightCurrent;
            rightCurrent.next = leftForwardptr;
            rightBackTrack.next = rightForwardptr;
            leftCurrent = leftForwardptr;
            leftBackTracePtr = leftCurrent;
            rightCurrent = middle.next;
        }
        leftForwardptr = leftForwardptr.next;
        leftBackTracePtr.next = middle;
        middle.next = leftForwardptr;

        return a;

    }

    private static void reverseListOnWards(Node node) {
        Node startNode = node.next;
        Node current = node.next;
        node.next = null;
        Node previous = null;
        Node next = node;
        while (current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        node.next = previous;

    }

    static Node getMiddleNodeOfTheList(Node a) {
        Node slowptr = a;
        Node fastPtr = a;
        while (fastPtr != null) {
            slowptr = slowptr.next;
            fastPtr = fastPtr.next;
            if (fastPtr != null) {
                fastPtr = fastPtr.next;
            }
        }
        return slowptr;

    }

    static class Node {
        public Node next;
        public int value;

        public Node(int value) {
            this.value = value;
        }

    }
}

爪哇8样式(功能性):

// Given
List<String> arr = Arrays.asList("a", "b", "c");
String first = arr.get(0);

arr = arr.subList(1, arr.size());
String folded = arr.stream()
            .reduce(first, (a, b) -> a + "," + b);

System.out.println(folded); //a,b,c

有没有这样的功能,但你可以创建类似以下内容,每当你需要调用它。

import java.util.Arrays;
import java.util.List;

public class FoldTest {
    public static void main( String [] args ) {
        List<String> list = Arrays.asList("a","b","c");
        String s = fold( list, ",");
        System.out.println( s );
    }
    private static String fold( List<String> l, String with  ) {
        StringBuilder sb = new StringBuilder();
        for( String s: l ) {
            sb.append( s ); 
            sb.append( with );
        }
        return sb.deleteCharAt(sb.length() -1 ).toString();

    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top