I want to group by multiple variables and sum with number and get the result with list in java. Like SQL group by, I want to merge the data record with the lowest string. What I want to do is the same as the SQL below,
select orderId, itemId, itemName, itemGenre, sum(number) as number
from item
group by itemId, itemName, itemGenre;
If data exist in the item table below,
orderId(PK), itemId, itemName, itemGenre, number
00-82-947, 8810, item name1, 01, 1
00-82-952, 8810, item name1, 01, 2
00-91-135, 8315, item name2, 02, 3
00-91-140, 8315, item name3, 02, 4
I expected the result to be below. When grouping with the orderId by 00-82-947 and 00-82-952, I want to get the lower one like SQL group by.
00-82-947, 8810, item name1, 01, 3,
00-91-135, 8315, item name2, 02, 3,
00-91-140, 8315, item name3, 02, 4
How can I implement this in Java? I think this works for me but in this case orderId that is not grouped by will be null so I need to create a new class to fill the orderId. http://codestudyblog.com/questions/sf/0421195604.html
This also would work but I want the result with list. So I need to covert it to map three times as I need to group by three times. Group by multiple field names in java 8
So I'm looking for a better way probably using java stream. As a reference, I leave the code.
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Item {
private String orderId;
private String itemId;
private String itemName;
private String itemGenre;
private Integer number;
}
Prepare data
final ArrayList<Item> items = new ArrayList<>();
items.add(new Item("00-82-947", "8810", "item name1", "01", 1));
items.add(new Item("00-82-952", "8810", "item name1", "01", 2));
items.add(new Item("00-91-135", "8315", "item name2", "02", 3));
items.add(new Item("00-91-140", "8315", "item name3", "02", 4));
System.out.println(items);
And I want print result to be below.
[Item(orderId=00-82-947, itemId=8810, itemName=item name1, itemGenre=01, number=3),
Item(orderId=00-91-135, itemId=8315, itemName=item name2, itemGenre=02, number=3),
Item(orderId=00-91-140, itemId=8315, itemName=item name3, itemGenre=02, number=4)]