Problem Statement: Write a Java program to create a method that takes an ArrayList of strings and returns a Map with each unique string as the key and its frequency as the value.
Here’s a Java program that demonstrates how to create a method that takes an ArrayList
of strings and returns a Map
with each unique string as the key and its frequency as the value.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StringFrequencyMapDemo {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>();
strings.add("apple");
strings.add("banana");
strings.add("apple");
strings.add("cherry");
strings.add("banana");
System.out.println("Original List: " + strings);
// Creating a Map with string frequencies
Map<String, Integer> frequencyMap = createStringFrequencyMap(strings);
System.out.println("String Frequency Map: " + frequencyMap);
}
// Method to create a Map with string frequencies
public static Map<String, Integer> createStringFrequencyMap(List<String> list) {
Map<String, Integer> frequencyMap = new HashMap<>();
for (String str : list) {
frequencyMap.put(str, frequencyMap.getOrDefault(str, 0) + 1);
}
return frequencyMap;
}
}
OUTPUT:
Original List: [apple, banana, apple, cherry, banana]
String Frequency Map: {banana=2, apple=2, cherry=1}
Explanation:
- Creating the List: We create an
ArrayList
namedstrings
and populate it with some strings, including duplicates. - Printing the Original List: We print the contents of the
strings
list usingSystem.out.println()
. - Creating the Frequency Map: We call the
createStringFrequencyMap()
method to create aMap
that stores the frequency of each unique string. createStringFrequencyMap()
Method: This method takes a list of strings as a parameter (list
) and returns aMap
where the keys are unique strings, and the values are their frequencies.- Iterating Through the List: We use a
for-each
loop to iterate through each string in thelist
. - Counting String Frequencies: Inside the loop, we use the
getOrDefault()
method of theMap
to get the current frequency of the string. If the string is not yet in the map, it defaults to 0. We then increment the frequency and put it back into the map. - Returning the Frequency Map: Finally, the method returns the
frequencyMap
, which contains the frequencies of each unique string in the input list.
By using a Map
to count the frequencies of each string in the list, the program effectively creates a Map
with each unique string as the key and its frequency as the value.
See also: Merge two sorted ArrayLists into a single sorted ArrayList.