-4

I want to do below data groupBy based on customerProduct using java

[{customerID=123,customerName=John,customerProduct=mobile},
{customerID=456,customerName=roach,customerProduct=laptop},
{customerID=678,customerName=david,customerProduct=mobile},
{customerID=678,customerName=abd,customerProduct=charger}]

How can we do it in java 8

and expecting like below

{
mobile= [
{customerID=123,customerName=John,customerProduct=mobile},
{customerID=678,customerName=david,customerProduct=mobile},
],
laptop= [{customerID=456,customerName=roach,customerProduct=laptop}],
charger= [{customerID=678,customerName=abd,customerProduct=charger}]
}
Gopi
  • 105
  • 1
  • 7
  • 24
  • What is your expected result from this sample data? – Shuwn Yuan Tee Feb 07 '18 at 11:04
  • We do not have the informations you have. From our point of view, we can't know what you want to do. Please add some context, some examples, etc... Also, you should rephrase your question to "Sort an array in Java", as sorting a List is way easier. – Turtle Feb 07 '18 at 11:06
  • 2
    Possible duplicate of [Java 8 streams group by 3 fields and aggregate by sum and count produce single line output](https://stackoverflow.com/questions/44089193/java-8-streams-group-by-3-fields-and-aggregate-by-sum-and-count-produce-single-l) – Mahendra Kapadne Feb 07 '18 at 11:52
  • Output should be like this { mobile= [ {customerID=123,customerName=John,customerProduct=mobile}, {customerID=678,customerName=david,customerProduct=mobile}, ], laptop= [{customerID=456,customerName=roach,customerProduct=laptop}], charger= [{customerID=678,customerName=abd,customerProduct=charger}] } – Gopi Feb 07 '18 at 12:29

1 Answers1

2

This should do it.

 stream().collect(Collectors.groupingBy(Customer::getCustomerProduct))
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • Without using pojo how can we do grouping. please help – Gopi Feb 07 '18 at 12:52
  • what do you meant by without using pojo. You have to give a field of a pojo to group. Or else how can you group. on what values will you group? – pvpkiran Feb 07 '18 at 13:06