In Java 8 and later, you can use the Collectors.groupingBy
method of the Collectors
class to create a Map
that maps each element in a List
to the number of occurrences of that element in the List
.
To create a Map
that maps elements in a List
to their occurrences, you can use the Collectors.groupingBy
method in combination with the Collectors.counting
method, which returns a Collector
that counts the number of input elements.
Here is an example of how you can use the Collectors.groupingBy
and Collectors.counting
methods to create a Map
that maps elements in a List
to their occurrences:
import java.util.List; import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; public class MyClass { public static void main(String[] args) { List<String> words = Arrays.asList("apple", "banana", "cherry", "apple", "banana"); Map<String, Long> map = words.stream() .collect(Collectors.groupingBy(s -> s, Collectors.counting())); System.out.println(map); // Outputs {apple=2, banana=2, cherry=1} } }
In this example, the words
List
contains five strings: "apple", "banana", "cherry", "apple", and "banana".
The Collectors.groupingBy
method groups the elements of the List
by their identity, and the Collectors.counting
method counts the number of elements.