Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for duplicates within a map in clojure?

So I have a list like the following:

({:name "yellowtail", :quantity 2} {:name "tuna", :quantity 1} 
{:name "albacore", :quantity 1} {:quantity 1, :name "tuna"})

My goal is to search the list of map items and find duplicates keys, if there are duplicates then increment the quantity. So in the list I have two tuna mapped elements that show up. I want to remove one and just increment the quantity of the other. So the result should be:

({:name "yellowtail", :quantity 2} {:name "tuna", :quantity 2} 
{:name "albacore", :quantity 1} )

With :quantity of tuna incremented to 2. I have attempted to use recur to do this without success, I'm not sure if recur is a good direction to run with. Could someone point me in the right direction?

like image 495
truffle Avatar asked Sep 08 '15 04:09

truffle


People also ask

How can I tell if a map has duplicate keys?

Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.

Can you have duplicates in a map?

Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys. Both HashSet and HashMap are not synchronized.

Can Hashmaps have duplicate values?

HashMap does not allow duplicate keys however it allows to have duplicate values. HashSet permits to have a single null value. HashMap permits single null key and any number of null values.


1 Answers

You can group-by :name your elements and then map through the grouped collection summing the values.

Something like this

(->> your-list 
  (group-by :name) 
  (map (fn [[k v]] 
         {:name k :quantity (apply + (map :quantity v))})))   

P.S. I assume you need to sum quantity of elements, because it's not clear what exactly you need to increment.

like image 191
JustAnotherCurious Avatar answered Sep 21 '22 12:09

JustAnotherCurious