Wap To Print Characters As Per Number Of Occurrences: The program InterviewPrograms47 aims to sort a given string based on the frequency of characters in ascending order.
Print Characters As Per the Number Of Occurrences
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; public class InterviewPrograms47 { /* * String input="1222bbbbcccaaaammmmm" * String output="1222cccbbbbaaaammmmm" * * We need to sort the string base on character size */ public static void main(String[] args) { System.out.println(sortFreq("1222bbbbcccaaaammmmm")); } public static String sortFreq(String str) { StringBuilder sb = new StringBuilder(); Map<Character, Integer> hm = new HashMap<>(); for (Character c : str.toCharArray()) { hm.put(c, hm.getOrDefault(c, 0) + 1); } System.out.println("frequency map of the String is " + hm); hm.entrySet().stream() .sorted(Map.Entry. <Character, Integer>comparingByValue()) .forEach(a -> {Character key = a.getKey(); int value = a.getValue(); for (int i = 0; i < value; i++) { sb.append(key); } }); System.out.println(sb); return sb.toString(); } }
Output
frequency map of the String is {1=1, a=4, 2=3, b=4, c=3, m=5} 1222cccaaaabbbbmmmmm 1222cccaaaabbbbmmmmm
Here’s a step-by-step explanation of the program:
- public static void main(String[] args): This is the entry point of the program. It calls the sortFreq method and passes the input string “1222bbbbcccaaaammmmm” as an argument.
- public static String sortFreq(String str): This method takes a string str as input and returns the sorted string based on character frequency. It uses a StringBuilder named sb to construct the sorted output.
- Map<Character, Integer> hm = new HashMap<>();: This line initializes a HashMap called hm to store character-frequency pairs. The program iterates through each character in the input string and updates the frequency in the map.
- hm.entrySet().stream()…: This part of the code uses the Java Stream API to sort the hm map based on the values (character frequencies) in ascending order. The entrySet() method provides a stream of key-value pairs, which is then sorted using Map.Entry.comparingByValue() comparator.
- forEach(a -> {…}: The sorted stream of key-value pairs is iterated using the forEach method. For each entry (character-frequency pair), the program extracts the character key and its corresponding frequency value.
- for (int i = 0; i < value; i++) {…}: For each character in the map, the program appends the character to the StringBuilder sb as many times as its frequency value.
- The final sorted string is obtained by converting the StringBuilder sb to a string using the toString() method and returned from the sortFreq method.
The program successfully sorts the input string “1222bbbbcccaaaammmmm” based on character frequency and produces the output “1222cccbbbbaaaammmmm”.
Alternative 1
In this program InterviewPrograms47_1, we are sorting a given string based on the frequency of characters in ascending order.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; public class InterviewPrograms47_1 { /* * String input="1222bbbbcccaaaammmmm" * String output="1222cccbbbbaaaammmmm" * * We need to sort the string base on character size */ public static void main(String[] args) { String input = "1222cccbbbbaaaammmmmmm"; Map<String, Integer> outputMap = new HashMap<>(); for (String letter : input.split("")) { outputMap.compute(letter, (k,v)->v==null?1:v+1); } System.out.println(outputMap); Map<Integer, List<String>> inversed = outputMap .entrySet() .stream().collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); inversed.values().forEach(list->list.sort(null)); new TreeMap<>(inversed).forEach((k,v)->v.forEach(letter-> System.out.print(letter.repeat(k)))); } }
Output
{a=4, 1=1, b=4, 2=3, c=3, m=7} 1222cccaaaabbbbmmmmmmm
Here’s a step-by-step explanation of the program:
- public static void main(String[] args): This is the entry point of the program. It starts by defining the input string “1222cccbbbbaaaammmmmmm”.
- Map<String, Integer> outputMap = new HashMap<>();: The program creates a HashMap called outputMap to store character-frequency pairs. It then iterates through each character in the input string and calculates its frequency using the compute method of the HashMap.
- Map<Integer, List<String>> inversed = …: The program converts the outputMap to a frequency-inverted map, where the keys are frequencies and the values are lists of characters with the corresponding frequency. It uses Java Stream API’s groupingBy and mapping collectors to achieve this.
- inversed.values().forEach(list->list.sort(null));: The characters in each frequency group are sorted alphabetically using the sort method.
- new TreeMap<>(inversed).forEach(…);: The frequency-inverted map is converted to a TreeMap, which automatically sorts the frequencies in ascending order. The forEach method is used to iterate through the sorted frequencies and their corresponding character lists.
- System.out.print(letter.repeat(k)): For each character in the sorted frequency group, the program prints the character repeated k times, where k is the frequency of that character.
By the end of the program, the output is obtained as “1222cccbbbbaaaammmmmmm”, where the string is sorted based on character frequency in ascending order.
Leave a Reply