Java Stream How to - Group by one property








The following code shows how to group by one property.

Example

/*from   ww  w  . j  a  v a 2s .  c  o  m*/
//revised from
//https://github.com/java8/Java8InAction



import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
  public static void main(String...args){
    List<Transaction> transactions = Arrays.asList( new Transaction(Currency.EUR, 1500.0),
        new Transaction(Currency.USD, 2300.0),
        new Transaction(Currency.GBP, 9900.0),
        new Transaction(Currency.EUR, 1100.0),
        new Transaction(Currency.JPY, 7800.0),
        new Transaction(Currency.CHF, 6700.0),
        new Transaction(Currency.EUR, 5600.0),
        new Transaction(Currency.USD, 4500.0),
        new Transaction(Currency.CHF, 3400.0),
        new Transaction(Currency.GBP, 3200.0),
        new Transaction(Currency.USD, 4600.0),
        new Transaction(Currency.JPY, 5700.0),
        new Transaction(Currency.EUR, 6800.0) );
    
    
    Map<Currency, List<Transaction>> transactionsByCurrencies = 
        transactions.stream().collect(Collectors.groupingBy(Transaction::getCurrency));
    System.out.println(transactionsByCurrencies);

  }
}
class Transaction {
  private final Currency currency;
  private final double value;

  public Transaction(Currency currency, double value) {
      this.currency = currency;
      this.value = value;
  }

  public Currency getCurrency() {
      return currency;
  }

  public double getValue() {
      return value;
  }

  @Override
  public String toString() {
      return currency + " " + value;
  }
}

enum Currency {
  EUR, USD, JPY, GBP, CHF
}

The code above generates the following result.