Find unique string in ArrayList with its frequency

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:

  1. Creating the List: We create an ArrayList named strings and populate it with some strings, including duplicates.
  2. Printing the Original List: We print the contents of the strings list using System.out.println().
  3. Creating the Frequency Map: We call the createStringFrequencyMap() method to create a Map that stores the frequency of each unique string.
  4. createStringFrequencyMap() Method: This method takes a list of strings as a parameter (list) and returns a Map where the keys are unique strings, and the values are their frequencies.
  5. Iterating Through the List: We use a for-each loop to iterate through each string in the list.
  6. Counting String Frequencies: Inside the loop, we use the getOrDefault() method of the Map 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.
  7. 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.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *