0

I've implemented a simple filtering method in Java by creating a composite String key (SaleType + SaleDate). Then I just put each sale by its unique key to a HashMap. As a result I have a HashMap with sales filtered by the SaleType + SaleDate key.

I've recently started learning Scala and want to try the same filtration logic with it. How may this be implemented using Scala opportunities? I suppose a filter method may be used. But how can I construct a String key from the Sale object and then put it to the uniqueSalesMap?

private static List<Sale> getUniqueSales(List<Sale> sales) {
    Map<String, Sale> uniqueSalesMap = Maps.newHashMap();
    for (Sale sale : sales) {
        String saleKey = sale.getSaleType() + sale.getSaleDate();
        uniqueSalesMap.put(saleKey, sale);
    }
    return new ArrayList<Sale>(uniqueSalesMap.values());
}
samba
  • 2,821
  • 6
  • 30
  • 85

3 Answers3

2

One way would using groupBy

sales.groupBy(s=>s.salesType +s.saleDate).values.map(_.head)
Arnon Rotem-Gal-Oz
  • 25,469
  • 3
  • 45
  • 68
1

Here is a relatively concise way that avoids constructing any intermediate Maps:

import collection.breakOut

val m: Map[String, Sale] = 
  (for (s <- sales) yield (s.getSaleType + s.getSaleDate, s))(breakOut)

m.values.toList

but to be honest, I don't see much of an advantage when compared to the original Java code. You could have written

val m = collection.mutable.HashMap.empty[String, Sale]
for (s <- sales) {
  m(s.getSaleType + s.getSaleDate) = s
}
m.values.toList

It doesn't seem any less clear to me.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
1

This does what you want, but not in the way that you wanted to do it, so I'm not sure if it counts as an answer or not.

sales.map(s => s.saleType + s.saleDate).distinct
Tim
  • 26,753
  • 2
  • 16
  • 29