Java 8流加入并返回多个值 [英] Java 8 stream join and return multiple values

查看:740
本文介绍了Java 8流加入并返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一段代码从.NET移植到Java,并绊倒了一个我想使用流映射和映射的场景。减少。

  class Content 
{
private String propA,propB,propC;
内容(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; }
}

列表<内容> 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内容的函数,并返回一个具有结果

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

我对Java很新,所以你可能会发现一些类似于更多的代码像C#比java

解决方案

你可以使用正确的lambda为 BinaryOperator in reduce function。

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


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"));

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" }

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

解决方案

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();

这篇关于Java 8流加入并返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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