Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The other answers will work, but <code>groupBy</code> is an expensive operation and inefficient if you have 10k employees and the first two have the same name.</p> <p><strong>1) Short method</strong>: (<code>distinct</code> internally builds a HashSet of all the values)</p> <pre><code>val names = employees.map(_.name) names.distinct != names </code></pre> <p><strong>2) Efficient method</strong>: (only traverses as much of the seq as it needs to before finding dupe)</p> <pre><code>def hasDupes(employees: Seq[Employee]): Boolean = { val names = collection.mutable.Set.empty[String] employees.foreach { e =&gt; if (names(e.name)) return true names += e.name } false } </code></pre> <p>You can write this as a <a href="http://pastebin.com/pdVf213x" rel="nofollow">one-liner</a> using a tail-recursive method, but the fact is that immutable sets are much slower than mutable ones so not much good if we're going for efficiency.</p> <p><strong>3) Off-the-wall method</strong>: (doesn't build a set at all, but starts a quicksort and quits (via a cheap exception) as soon as it finds two names the same. Should be efficient. )</p> <pre><code>class Dupe extends Throwable with util.control.NoStackTrace val dupeOrd = new Ordering[Employee] { def compare(x: Employee, y: Employee) = if (x.name == y.name) throw new Dupe else x.name compare y.name } def hasDupes(employees: Seq[Employee]) = try { employees.sorted(dupeOrd); false } catch { case e: Dupe =&gt; true } </code></pre> <p><strong>Benchmark</strong> of results, with method 0 being om-nom-nom's <code>groupBy</code> one, (time in ms for 1000 runs on 1000 employee Vector, no duplicates):</p> <pre><code>method time Early return if duplicate found 0 (groupBy) 1560 No 1 (distinct) 329 No 2a (mutable.Set) 255 Yes 2b (immutable.Set) 1414 Yes 3 (sorting) 666 Yes //242 if employees already in name order </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload