Sort A String According To The Frequency Of Characters: The program InterviewPrograms51 aims to rearrange the characters of a given input string in descending order based on their frequency of occurrence.
Sort A String According To The Frequency Of Characters
To solve this program, we have taken the help of various Java topics like:
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class InterviewPrograms51 { /* * Input: tomorrow * Output: ooorrtmw */ public static void main(String[] args) { String input = "tomorrow"; Map<Character, Integer> map = StringManipulation(input); // sort and print List<Map.Entry<Character, Integer>> toSort = new ArrayList<>(map.entrySet()); toSort.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); for ( Map.Entry<Character, Integer> x : toSort ) { int count = x.getValue(); while ( count > 0 ) { System.out.print ( x.getKey ( ) ) ; count-- ; } } } private static Map<Character, Integer> StringManipulation(String input) { Map<Character, Integer> map=new LinkedHashMap<>(); for(char ch : input.toCharArray()) if(map.containsKey(ch)) map.put(ch, map.get(ch)+1); else map.put(ch, 1); return map; } }
Output
ooorrtmw
Here’s how the program works:
- The input string “tomorrow” is given as the input.
- The program uses the StringManipulation() method to create a map called map, where the keys are characters from the input string, and the values are their corresponding frequencies.
- The StringManipulation() method iterates through each character in the input string. If the character is already present in the map, it increments its count by 1. Otherwise, it adds the character to the map with a count of 1.
- The map now contains the frequencies of each character in the input string.
- The program then creates a list toSort with the entries of the map. This step is done to sort the characters based on their frequencies.
- The list toSort is sorted in descending order of frequencies using Map.Entry.comparingByValue(Comparator.reverseOrder()).
- Finally, the sorted list is iterated, and for each character and its corresponding frequency, the program prints the character count number of times to the console.
In this specific case, the program will output:
ooorrtmw
The output represents the rearranged characters from the input string “tomorrow” in descending order of their frequencies. The character ‘o’ occurs 3 times, ‘r’ occurs 2 times, ‘t’ occurs 1 time, ‘m’ occurs 1 time, and ‘w’ occurs 1 time in the input string.
Leave a Reply