View Category

Define an empty map

ruby
map = {}
java
Map map = new HashMap();
perl
# %map = {}
# This was wrong, that would have created a hash with one key
# of the stringified hash reference (HASH(0xNUMBERSHERE)) and a
# value of 'undef', as well as triggering a
# "Reference found where even-sized list expected" with the warnings
# pragma enabled

my %map;
groovy
def map = [:]
Map map = new HashMap();
scala
val map = mutable.Map.empty
val map = mutable.HashMap.empty[String, Int]
val map = Map()
python
map = {}
cpp
Hashtable^ hash = gcnew Hashtable;
Generic::Dictionary<String^, String^>^ dict = gcnew Generic::Dictionary<String^, String^>();
std::map<int, std::string> m;
fsharp
let map = Map.empty
let map = new Generic.Dictionary<string, string>()
let map = new Hashtable()
erlang
Map = dict:new(),
Map = orddict:new(),
Map = gb_trees:empty(),
Map = ets:new(the_map_name, [set, private, {keypos, 1}]),
ocaml
module StringMap = Map.Make (String)
let m = StringMap.empty
let m = Hashtbl.create 42
php
$map = array();
$map = array("" => "");
haskell
import qualified Data.Map as M

emptyMap = M.empty

clojure
(def m {})
fantom
map := [:]
go
m := make(map[int]string)

Define an unmodifiable empty map

ruby
map = {}.freeze
java
Map empty = Collections.EMPTY_MAP;
SortedMap empty = MapUtils.EMPTY_SORTED_MAP;
perl
# perl does not provide unmodifiable maps/hashes, but you could use "constant
# functions", if you really need them
# 2011-07-06 Not actually true, see Hash::Util::lock_hash;

sub MAP () { {} }
use Hash::Util qw/lock_hash/;
# two lines
my %hash;
lock_hash(%hash);
# or in one line
lock_hash(my %locked_hash);
groovy
empty = Collections.EMPTY_MAP
map = [:].asImmutable()
def empty = MapUtils.EMPTY_SORTED_MAP
def empty = ImmutableMap.of()
scala
val map = immutable.Map.empty
val map = immutable.TreeMap.empty[String, Int]
val map = Map()
python
import collections
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()
cpp
const std::map<T1,T2> immutable_map_instance_of_type_t1_to_t2;
fsharp
// Most native fsharp data structures are immutable - updating a 'map' sees a modified copy created
let map = Map.empty
erlang

% Erlang data structures are immutable - updating a 'map' sees a modified copy created
Map = dict:new(),
ocaml
(* OCaml maps are functional data structures (so are immutable) *)
module StringMap = Map.Make (String)
let m = StringMap.empty
php
/* It's not possible to define an array as a constant
* Instead we can use the serialize-function */

$fruits = array("apple", "banana", "orange");
define("FRUITS", serialize($fruits));
echo FRUITS; // a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
$my_fruits = unserialize(FRUITS); // and normal array again
haskell
import qualified Data.Map as Map

output :: Map.Map k v
output = Map.empty
clojure
; Clojure maps are immutable
(def m {})
fantom
map := [:].ro

Define an initial map

Define the map {circle:1, triangle:3, square:4}
ruby
shapes = {'circle'=>1, 'triangle'=>3, 'square'=>4}
shapes = Hash['circle', 1, 'triangle', 3, 'square', 4]
shapes = { :circle => 1, :triangle => 3, :square => 4 }
java
Map shapes = new HashMap();
shapes.put("circle", 1);
shapes.put("triangle", 3);
shapes.put("square", 4);
Map shapes = new HashMap() {{ put("circle",1); put("triangle",3); put("square",4); }}
perl
%map = (circle => 1, triangle => 3, square => 4);
groovy
shapes = [circle:1, triangle:3, square:4]
// if you require a specific type of map ...
LinkedHashMap shapes1 = [circle:1, triangle:3, square:4]
Properties shapes2 = [circle:1, triangle:3, square:4]
TreeMap shapes3 = [circle:1, triangle:3, square:4]
shapes4 = [circle:1, triangle:3, square:4] as ConcurrentHashMap // as variation
scala
val shapes = immutable.TreeMap("circle" -> 1, "triangle" -> 3, "square" -> 4)
val shapes = mutable.Map.empty[String, Int]

shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
var shapes = immutable.Map.empty[String, Int]

shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
val shapes = immutable.Map(
"circle" -> 1,
"triangle" -> 3,
"square" -> 4
)
val map = Map("circle" -> 1, "triangle" -> 3, "square" -> 4)
python
shapes = {'circle': 1, 'square': 4, 'triangle': 2}
shapes = dict(circle=1, square=4, triangle=2)
cpp
Hashtable^ shapes = gcnew Hashtable;

shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
Generic::Dictionary<String^, int>^ shapes = gcnew Generic::Dictionary<String^, int>();

shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
map<string, int> shapes;

shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;
fsharp
let shapes = Map.ofList [("circle", 1); ("triangle", 3); ("square", 4)]
let shapes = Map.empty.Add("circle", 1).Add("triangle", 3).Add("square", 4)
let shapes = new Generic.Dictionary<string, int>()
shapes.Add("circle", 1)
shapes.Add("triangle", 3)
shapes.Add("square", 4)
let shapes = Map [("circle", 1); ("triangle", 3); ("square", 4)]
erlang
Map = dict:from_list([{circle, 1}, {triangle, 3}, {square, 4}]),
Map0 = dict:new(),

% Erlang variables are 'single-assignment' i.e. they cannot be reassigned
Map1 = dict:store(circle, 1, Map0),
Map2 = dict:store(triangle, 3, Map1),
Map3 = dict:store(square, 4, Map2),
Map0 = gb_trees:empty(),

Map1 = gb_trees:enter(circle, 1, Map0),
Map2 = gb_trees:enter(triangle, 3, Map1),
Map3 = gb_trees:enter(square, 4, Map2),
Map = gb_trees:from_orddict(lists:keysort(1, [{circle, 1}, {triangle, 3}, {square, 4}])),
Map = ets:new(the_map_name, [ordered_set, private, {keypos, 1}]),
ets:insert(Map, [{circle, 1}, {triangle, 3}, {square, 4}]),
ocaml
module StringMap = Map.Make (String)

let m0 = StringMap.empty

let m1 = StringMap.add "circle" 1 m0
let m2 = StringMap.add "triangle" 3 m1
let m3 = StringMap.add "square" 4 m2
let m = Hashtbl.create 42;;

Hashtbl.replace m "circle" 1;;
Hashtbl.replace m "triangle" 3;;
Hashtbl.replace m "square" 4;;
php
$map = array("circle" => 1, "triangle" => 3, "square" => 4);
haskell
import qualified Data.Map as M

initialMap = M.fromList [("circle", 1), ("triangle", 3), ("square", 4)]

clojure
(def m '{circle 1 triangle 1 square 4})
fantom
map := ["circle":1, "triangle":2, "square":4]
go
m := map[string]int{ "circle": 1, "square": 4, "triangle": 2 }

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
ruby
puts "ok" if map.has_key?('mary')
puts "ok" if map['mary'] # Only works if map entry can't be nil or false
java
if (pets.containsKey("mary")) System.out.println("ok");
perl
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if ($pets{'mary'});
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if $pets{'mary'};
print 'ok' if $pets{mary};
print 'ok' if exists $pets{mary}
Starting with a previously suggested solution:

%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if $pets{'mary'};

.. there is a case where this will not work as expected- for the case where mary => 0 ..

suggest instead to use the following conditional check if a value of 0 is allowable.:

print 'ok - is defined' if defined $pets{'mary'};
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.containsKey('mary')) println 'ok'
pets = [joe:'cat', mary:'turtle', bill:'canary']
if(pets.mary) println 'ok'
scala
if (pets.contains("mary")) println("ok")
map.get("mary").foreach(println("ok"))
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"
cpp
if (pets->ContainsKey("mary")) Console::WriteLine("ok");
if (pets.find("mary") != pets.end()){
std::cout << "ok" << std::endl;
}
if (pets.count("mary") > 0)
cout << "ok" << endl;
fsharp
if (Map.mem "mary" pets) then printfn "ok"
if pets.ContainsKey("mary") then printfn "ok"
erlang
dict:is_key(mary, Pets) andalso begin io:format("ok~n"), true end.
IsMember = ets:member(Pets, mary), if (IsMember) -> io:format("ok~n") ; true -> false end.
case gb_trees:lookup(mary, Pets) of none -> false ; _ -> io:format("ok~n") end.
ocaml
module StringMap = Map.Make (String)

let map =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let () =
if StringMap.mem "mary" map
then print_endline "OK"
let () =
let map = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add map key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

if Hashtbl.mem map "mary" then print_endline "OK"
php
if (array_key_exists("mary", $pets)) {
echo "ok";
}
if (isset($pets["mary"])) { // only works if $pets["mary"] can't be false or 0
echo "ok";
}
haskell
import qualified Data.Map as M
import Control.Monad (when)

pets = M.fromList [("joe", "cat"), ("mary", "turtle"), ("bill", "canary")]

checkMary = when (M.member "mary" pets) (print "ok")

clojure
(if (contains? '{joe cat mary turtle bill canary} 'mary)
(println "ok"))
(when (contains? pets "mary")
(println "ok"))
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
if (map.containsKey("mary")) echo("ok")
go
m := map[string]string{ "joe": "cat", "mary": "turtle", "bill": "canary" }
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
ruby
puts map['joe']
java
String pet = pets.get("joe");
perl
%pets = (joe => 'cat', mary => 'turtle', bill=>'canary');
print $pets{joe};
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
assert pets['joe'] == 'cat'
assert pets.joe == 'cat'
scala
if (pets.contains("joe")) println(pets("joe"))
println(pets.getOrElse("joe", "*** no pet owned ***"))
pets("joe")
python
print pets['joe']
cpp
if (pets->ContainsKey("joe")) Console::WriteLine(pets["joe"]);
cout << pets["joe"] << endl;
fsharp
if (Map.mem "joe" pets) then printfn "%s" (Map.find "joe" pets)
if (pets |> Map.exists (fun key _ -> key = "joe")) then printfn "%s" (Map.find "joe" pets)
let key = "joe"
match (pets |> Map.tryfind key) with
| Some(value) -> printfn "%s" value
| None -> printfn "Key %s not found" key
if pets.ContainsKey("joe") then printfn "%s" pets.["joe"]
if pets.ContainsKey("joe") then printfn "%s" (pets.["joe"] :?> string)
erlang
dict:is_key(joe, Pets) andalso begin io:format("~w~n", [dict:fetch(joe, Pets)]), true end.
case dict:find(joe, Pets) of error -> false ; {ok, Pet} -> io:format("~w~n", [Pet]) end.
IsMember = ets:member(Pets, joe), if (IsMember) -> io:format("~w~n", [ets:lookup_element(Pets, joe, 2)]) ; true -> false end.
case ets:match(Pets, {joe, '$1'}) of [] -> false ; [[Pet]] -> io:format("~w~n", [Pet]) end.
case gb_trees:lookup(joe, Pets) of none -> false ; {value, Pet} -> io:format("~w~n", [Pet]) end.
ocaml
module StringMap = Map.Make (String)

let map =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let () =
try
let pet = StringMap.find "joe" map in
Printf.printf "Joe's pet is a %s.\n" pet
with Not_found ->
prerr_endline "No pet found for Joe."
let () =
let map = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add map key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

try
let pet = Hashtbl.find map "joe" in
Printf.printf "Joe's pet is a %s.\n" pet
with Not_found ->
prerr_endline "No pet found for Joe."
php
echo $pets["joe"];
haskell
import qualified Data.Map as M

pets = M.fromList [("joe", "cat"), ("mary", "turtle"), ("bill", "canary")]
retrieve = print $ M.findWithDefault "Not found" "joe" pets
clojure
(def pets '{joe cat mary turtle bill canary})

(println (get pets 'joe))
fantom
map := ["joe":"cat", "mary":"turtle", "bill":"canary"]
pet := map["joe"]
echo("pet=$pet")
go
fmt.Println(pets["joe"])

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
ruby
pets['rob']='dog'
java
pets.put("rob", "dog");
perl
$pets{rob} = 'dog';
groovy
pets['rob'] = 'dog'
pets.rob = 'dog'
pets.put('rob', 'dog')
scala
pets += "rob" -> "dog"
python
pets['rob'] = 'dog'
cpp
pets->Add("rob", "dog");
pets["rob"] = "dog";
fsharp
pets <- (Map.add "rob" "dog" pets)
pets.Add("rob", "dog")
erlang
Pets1 = dict:store(rob, dog, Pets0).
ets:insert(Pets, {rob, dog}).
Pets1 = gb_trees:enter(rob, dog, Pets0).
ocaml
module StringMap = Map.Make (String)

let pets = StringMap.add "rob" "dog" StringMap.empty
let () =
let map = Hashtbl.create 42 in
Hashtbl.replace map "rob" "dog"
php
$pets["rob"] = "dog";
haskell
import qualified Data.Map as M

pets = M.insert "rob" "dog" M.empty
clojure
(assoc {} 'rob 'dog)
fantom
map["rob"] = "dog"
go
pets["rob"] = "dog"

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
ruby
puts map.delete :bill
java
System.out.println(pets.remove("bill"))
perl
print delete $pets{bill};
groovy
pets = [joe:'cat', mary:'turtle', bill:'canary']
println pets.remove('bill')
scala
val pet = pets("bill") ; pets -= "bill" ; println(pet)
println(pets.removeKey("bill") match { case Some(pet) => pet ; case None => "***" })
python
print pets.pop('bill')
cpp
if (pets->ContainsKey("bill"))
{
String^ value = safe_cast<String^>(pets["bill"]); pets->Remove("bill");
Console::WriteLine("{0}", value);
}
fsharp
let key = "bill"
match (pets |> Map.tryFind key) with
| Some(value) -> pets <- (Map.remove key pets) ; printfn "%s : %s removed" key value
| None -> printfn "Key %s not found" key
let key = "bill"
let entry = if (pets.ContainsKey(key)) then Some(pets.[key]) ; else None
pets.Remove(key)

match entry with
| Some(value) -> printfn "%s" value
| None -> printfn "key not found"
erlang
Pet = dict:fetch(bill, Pets0), Pets1 = dict:erase(bill, Pets0), io:format("~w~n", [Pet]),
Pet = ets:lookup_element(Pets, bill, 2), ets:delete(Pets, bill), io:format("~w~n", [Pet]),
{value, Pet} = gb_trees:lookup(bill, Pets0), Pets1 = gb_trees:delete(bill, Pets0), io:format("~w~n", [Pet]),
ocaml
module StringMap = Map.Make (String)

let pets =
List.fold_left (fun map (key, value) ->
StringMap.add key value map
) StringMap.empty [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")]

let get_and_rem key m =
try
let value = StringMap.find key m in
let rm = StringMap.remove key m in
Some (value, rm)
with Not_found ->
None

let () =
let key = "bill" in
match get_and_rem key pets with
| Some (found, new_pets) ->
Printf.printf "%s : %s removed\n" key found
| None ->
Printf.printf "Key %s not found" key
let get_and_rem m key =
try
let value = Hashtbl.find m key in
Hashtbl.remove m key;
Some value
with Not_found ->
None

let () =
let pets = Hashtbl.create 42 in
List.iter (fun (key, value) ->
Hashtbl.add pets key value
) [("joe", "cat"); ("mary", "turtle"); ("bill", "canary")];

let key = "bill" in
match get_and_rem pets key with
| Some found ->
Printf.printf "%s : %s removed\n" key found
| None ->
Printf.printf "Key %s not found" key
php
$last = array_pop($pets); // removes last key and assign it to the variable
echo $last;
$last = $pets[count($pets)-1];
echo $last;
unset($last);
$bill = $pets["bill"];
echo $bill;
unset($bill);
print_r(array_pop($pets));
haskell
import qualified Data.Map as M

main = do
let pets = M.fromList [("joe", "cat"), ("mary", "turtle"), ("bill", "canary")]
pets2 = M.delete "bill" pets
print $ maybe "" id (M.lookup "bill" pets)
print pets2
clojure
; Maps are immutable
; The following expression will return a new map without the 'bill key
(let [pets '{joe cat mary turtle bill canary}]
(println (get pets 'bill))
(dissoc pets 'bill))
fantom
pet := map.remove("bill")
echo ("pet=$pet")
go
fmt.Println(pets["bill"])
delete(pets, "bill")
fmt.Println(pets["bill"])
pets["bill"] = "", false

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list = %w{a b a c b b}

histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end

p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
java
Map map = new HashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
LinkedMap histogram = new LinkedMap();

for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);
perl
foreach(@list) {
$histogram{$_}++;
}
$histogram{$_}++ for @list;
groovy
histogram = [:]
list.each { item ->
if (!histogram.containsKey(item)) histogram[item] = 0
histogram[item]++
}
histogram = [:]
list.each { histogram[it] = (histogram[it] ?: 0) + 1 }
def histogram = [:].withDefault{ 0 }
list.each { histogram[it] += 1 }
histogram
list.inject([:].withDefault{ 0 }) { map, nr -> map[nr] += 1; map}
scala
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}

list.groupBy(identity).mapValues(_.size)
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1

h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)
cpp
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;
fsharp
let histogram = (List.foldLeft (fun (acc : Map<char, int>) (e : char) -> if (Map.mem e acc) then (Map.add e ((Map.find e acc) + 1) acc) ; else (Map.add e 1 acc)) (Map.empty) list)
let histogram list =
let rec histogram' list' dict' =
match list' with
| [] -> dict'
| x :: xs ->
match Map.tryFind x dict' with
| Some(Value) -> histogram' xs (Map.add x (Value + 1) dict')
| None -> histogram' xs (Map.add x 1 dict')
histogram' list Map.empty

// ------

let histogram' = histogram list
let histogram = (List.foldLeft (fun (acc : Generic.Dictionary<char, int>) (e : char) -> (if acc.ContainsKey(e) then acc.[e] <- acc.[e] + 1 ; else acc.Add(e, 1)) ; acc) (new Generic.Dictionary<char, int>()) list)
let histogram =
list
|> Seq.groupBy (fun a -> a)
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
|> Map.ofSeq
erlang
% Imperative Solution
Histogram = histogram(List),
% Functional (1) Solution
Histogram = histogram(List),
lists:foldl(fun(Elem, OldDict) ->
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
ocaml
module StringMap = Map.Make (String)

let histogram lst =
List.fold_left (fun m v ->
let n =
if StringMap.mem v m
then succ (StringMap.find v m)
else 1
in
StringMap.add v n m
) StringMap.empty lst

let () =
let h = histogram ["a"; "b"; "a"; "c"; "b"; "b"] in
StringMap.iter (fun key value ->
Printf.printf " %s: %d\n" key value
) h
csharp
using System.Collections.Generic;
using System.Linq;

// This is a "functional" C# approach

// NOTE: In C# "maps" are of type Dictionary<Tkey, TValue>
// so our histogram map is of type Dictionary<object, int>
public class HistogramMap {
public Dictionary<object, int> FromList(List<object> list) {
// The "Aggregate" method works like "inject" in many other languages.
return list.Aggregate(
new Dictionary<object, int>(),
(map, obj) => {
// If this is the first time we've seen this obj, set the count to 0
if (!map.ContainsKey(obj)) map[obj] = 0;

// Increment the count
map[obj]++;

// Return the map for the next iteration.
// NOTE: This does NOT return from our "FromList" method
return map;
}
);
}

public static void Main() {
// Create our Histogram Map from a new list
var map = new HistogramMap().FromList(
new List<object>() { 'a', 'b', 'a', 'c', 'b', 'b' }
);

// This just prints the result
System.Console.WriteLine (
string.Join (", ",
// "Select" works like "map" or "collect" in many other languages
map.Select( kvp =>
string.Format("{0} : {1}", kvp.Key, kvp.Value)
).ToArray()
)
);
}
}
new[] {"a","b","a","c","b","b"}
.GroupBy(s => s)
.Select(s => new { Value = s.Key, Count = s.Count() })
.ToList()
.ForEach(e => Console.WriteLine("{0} : {1} ", e.Value, e.Count));
php
$list = array("a","b","a","c","b","b");
$map = array_count_values($list);
haskell
import Data.List
import qualified Data.Map as Map

histogram :: Ord a => [a] -> Map.Map a Int
histogram xs = Map.fromList [ (head l, length l) | l <- group (sort xs) ]

output :: Map.Map String Int
output = histogram ["a","b","a","c","b","b"]
import Control.Arrow
import Data.List
import qualified Data.Map as Map
import System.Random

histogram :: Ord a => [a] -> Map.Map a Int
histogram = Map.fromList . map (head &&& length) . group . sort

main = print . histogram . take 1000 . randomRs (1::Int, 100) =<< newStdGen
import qualified Data.Map as Map

histogram :: [String] -> Map.Map String Int
histogram ss = foldl addElem Map.empty ss
where addElem m e = Map.insertWith (+) e 1 m

output :: Map.Map String Int
output = histogram ["a","b","a","c","b","b"]
clojure
(let [l '[a b a c b b]]
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
(->> [:a :b :a :c :b :b]
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
(frequencies ["a","b","a","c","b","b"])
(frequencies '[a b a c b b])
fantom
list := ["a","b","a","c","b","b"]
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)
go
var maplist = make(map[string]int)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
lengths = list.group_by {|x| x.size}
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;

for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
MultiValueMap map = new MultiValueMap();
for (Object item : list) map.put(((String) item).length(), item);
perl
@list = qw(one two three four five);
push @{$map{length($_)}}, $_ for (@list);
groovy
map = ['one', 'two', 'three', 'four', 'five'].groupBy{ it.size() }
scala
list foreach { (x) => map += x.length -> (x :: map.getOrElse(x.length, Nil)) }
list foreach { (x) => map += x.length -> (map.getOrElse(x.length, Nil) ::: List(x)) }
List("one", "two", "three", "four", "five") groupBy (_ size)
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
cpp
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
fsharp
let catmap = (List.foldLeft (fun (acc : Map<int, List<string> >) (e : string) -> if (Map.mem e.Length acc) then (Map.add e.Length ((Map.find e.Length acc) @ [e]) acc) ; else (Map.add e.Length [e] acc)) (Map.empty) list)
let lengthMap =
["one"; "two"; "three"; "four"; "five"]
|> Seq.groupBy (fun s -> s.Length)
|> Seq.map (fun (length, entries) -> (length, entries |> List.ofSeq))
|> Map.ofSeq
erlang
% Imperative Solution
CatList = categorise(List),
% Functional (1) Solution
CatList = categorise(List),
ocaml
let map =
List.fold_left (fun map v ->
let len = String.length v in
let before =
try IntMap.find len map
with Not_found -> [] in
IntMap.add len (v :: before) map
) IntMap.empty ["one"; "two"; "three"; "four"; "five"]
csharp
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
php
foreach ($array as $m) {
$l = strlen($m);
$map[$l][] = $m;
}
arsort($map);
haskell
import qualified Data.Map as Map

groupInMapBy :: Ord k => (a -> k) -> [a] -> Map.Map k [a]
groupInMapBy f = foldr (\a -> Map.insertWith (++) (f a) [a]) Map.empty

output :: Map.Map Int [String]
output = groupInMapBy length ["one", "two", "three", "four", "five"]
import Data.List (groupBy, sortBy)
import Data.Function (on)

groupInPairsBy :: Ord k => (a -> k) -> [a] -> [(k, [a])]
groupInPairsBy f = map (\xs -> (f (head xs), xs)) .
groupBy ((==) `on` f) . sortBy (compare `on` f)

output :: [(Int, [String])]
output = groupInPairsBy length ["one", "two", "three", "four", "five"]
clojure
(loop [m {}
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
(group-by count ["one" "two" "three" "four" "five"])
fantom
list := ["one", "two", "three", "four", "five"]
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)