Java Streams API汇总索引的列表

时间:2015-05-22 18:04:48

标签: java java-8 java-stream

我想知道是否有更有效的方法来对所有树列表求和 - 在相同的索引处对它们的值求和。

我之所以问它是因为,可能使用Streams API,它可以使它更通用,适用于任意数量的列表。

void Main()
{
   DataTable one = new DataTable();
   one.Columns.Add("ID");
   one.Columns.Add("PCT");
   one.Rows.Add("1", "0.1");
   one.Rows.Add("2", "0.2");
   one.Rows.Add("3", "0.3");
   DataTable two = new DataTable();
   two.Columns.Add("ID");
   two.Columns.Add("PCT");
   two.Columns.Add("OldPCT");
   two.Rows.Add("1", "0.1", "0");
   two.Rows.Add("2", "0.1", "0");
   two.Rows.Add("3", "0.9", "0");
   two.Columns.Remove("OldP

   DataTable three = two.AsEnumerable().Except(one.AsEnumerable(),new RowEqualityComparer()).CopyToDataTable();
   foreach (DataRow dr in three.AsEnumerable())
   {
       string strID = dr[0].ToString();
       string strPCT = dr[1].ToString();
   }
}


class RowEqualityComparer : IEqualityComparer<DataRow>
{
   public bool Equals(DataRow b1, DataRow b2)
   {
     if ((b1.Field<string>("ID") == b2.Field<string>("ID")) && (b1.Field<string>("PCT") == b2.Field<string>("PCT")))
     {
       return true;
     }
     else
     {
       return false;
     }
   }

   public int GetHashCode(DataRow bx)
   {
     return (bx.Field<string>("ID")+bx.Field<string>("PCT")).GetHashCode();
   }
}

感谢任何见解。

1 个答案:

答案 0 :(得分:5)

这个怎么样:

List<List<Double>> lists = ...;

// ensure all lists are same size, and get size
int[] sizes = lists.stream().mapToInt(List::size).distinct().toArray();
if (sizes.length != 1)
    throw ...
int size = sizes[0];

double[] sums =
    IntStream.range(0, size)
             .mapToDouble(i -> lists.stream().mapToDouble(list -> list.get(i)).sum())
             .toArray();