"Getting the number of occurrences for each element in the list" means In particular,
["a", "b", "c", "c", "b", "c",]
From
{"a": 1, "b": 2, "c": 3,}
I will refer to the operation to obtain.
Let's do this in several languages.
For Python
import collections
list = ["a", "b", "c", "c", "b", "c",]
counter = collections.Counter(list)
print(dict(counter))
# -> {'a': 1, 'b': 2, 'c': 3}
Reference: [python --How to count the frequency of the elements in a list? --Stack Overflow](https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements- in-a-list)
For PHP
$list = ["a", "b", "c", "c", "b", "c",];
$counts = array_count_values($list);
echo json_encode($counts) . PHP_EOL;
// -> {"a":1,"b":2,"c":3}
Reference: PHP: array_count_values --Manual
For Java
// import java.util.*;
// import java.util.stream.Collectors;
// import java.util.function.Function;
List<String> list = Arrays.asList("a", "b", "c", "c", "b", "c");
Map<String, Long> counts = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counts);
// -> {a=1, b=2, c=3}
Reference: [java --How to count the number of occurrences of an element in a List --Stack Overflow](https://stackoverflow.com/questions/505928/how-to-count-the-number-of-occurrences-of -an-element-in-a-list)
At first I tried it with Laravel as follows, but there is PHP is a standard function itself. You did ......... As expected PHP ……
When using Laravel's Collection
$list = ["a", "b", "c", "c", "b", "c",];
$counts = collect($list)
->groupBy(null)
->map->count()
;
echo json_encode($counts) . PHP_EOL;
// -> {"a":1,"b":2,"c":3}
Recommended Posts