I have a question that's similar to yesterday's question.
I've got this List<object[]>
List<object[]> olst = new List<object[]>();
olst.Add(new object[] { "AA1", "X", 1, 3.50 });
olst.Add(new object[] { "AA2", "Y", 2, 5.20 });
olst.Add(new object[] { "AA2", "Y", 1, 3.50 });
olst.Add(new object[] { "AA1", "X", 1, 3.20 });
olst.Add(new object[] { "AA1", "Y", 2, 5.30 });
I need to produce List<object[]> to hold this:
"AA1", "X", 2, 6.70
"AA2", "Y", 3, 8.70
"AA1", "Y", 2, 5.30
In other words, I need to group olst by the 1st and 2nd elements of each object[] and sum 3rd and 4th.
I could use a for loop, but I was hoping someone could help me using lambda expressions and/or linq to accomplish this.
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL's GROUP BY clause.
In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
You could create a list of Object like List<Object> list = new ArrayList<Object>() . As all classes implementation extends implicit or explicit from java. lang. Object class, this list can hold any object, including instances of Employee , Integer , String etc.
List<object[]> olst = new List<object[]>();
olst.Add(new object[] { "AA1", "X" });
olst.Add(new object[] { "AA2", "Y" });
olst.Add(new object[] { "AA2", "Y" });
olst.Add(new object[] { "AA1", "X" });
olst.Add(new object[] { "AA1", "Y" });
var result = from ol in olst
group ol by new {p1 = ol[0], p2 = ol[1]}
into g
select g.First();
Something like this?
You need to group by an anonymous type, then sum the third and fourth columns:
List<object[]> grouped = olst
.GroupBy(o => new { Prop1 = o[0].ToString(), Prop2 = o[1].ToString() })
.Select(o => new object[]
{
o.Key.Prop1,
o.Key.Prop2,
o.Sum(x => (int)x[2]),
o.Sum(x => (double)x[3])
})
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With