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());
}
2

3 Answers 3

2

One way would using groupBy

sales.groupBy(s=>s.salesType +s.saleDate).values.map(_.head)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.