Java 8 流连接并返回多个值多个、Java

2023-09-07 01:38:08 作者:囧男

我正在将一段代码从 .NET 移植到 Java,并偶然发现了我想使用流来映射 &减少.

I'm porting a piece of code from .NET to Java and stumbled upon a scenario where I want to use stream to map & reduce.

class Content
{
  private String propA, propB, propC;
  Content(String a, String b, String c)
  {
    propA = a; propB = b; propC = c;
  }
  public String getA() { return propA; }
  public String getB() { return propB; }
  public String getC() { return propC; }
}

List<Content> contentList = new ArrayList();
contentList.add(new Content("A1", "B1", "C1"));
contentList.add(new Content("A2", "B2", "C2"));
contentList.add(new Content("A3", "B3", "C3"));

我想写一个函数,可以通过 contentlist 的内容进行流式传输并返回一个带有结果的类

I want to write a function that can stream through the contents of contentlist and return a class with result

content { propA = "A1, A2, A3", propB = "B1, B2, B3", propC = "C1, C2, C3" }

我对 Java 还很陌生,所以您可能会发现一些代码更像 C# 而不是 java

I'm fairly new to Java so you might find some code that resembles more like C# than java

推荐答案

您可以为 BinaryOperator 在 reduce 函数中.

You can use proper lambda for BinaryOperator in reduce function.

Content c = contentList
            .stream()
            .reduce((t, u) -> new Content(
                                  t.getA() + ',' + u.getA(),
                                  t.getB() + ',' + u.getB(), 
                                  t.getC() + ',' + u.getC())
                   ).get();