I am trying to write a program to order a list of strings by most least frequent characters within the list. For example, if the list was [apple, orange, banana]
the letter frequency within the list would be a – 5, n – 3, p – 2, e – 2, l- 1, o – 1, r – 1, g – 1, b – 1. Since orange contains the most least frequent letters, the program would return orange, then apple then banana.
So far I’ve written the code that orders all the letters in the list by frequency. But I need to apply that to find which string contains the most least frequent letters.
Here is my code:
Map<Character, Integer> elemCount = new LinkedHashMap<>(); for (String word : words) { for (int i = 0; i < word.length(); i++) { if (elemCount.containsKey(word.charAt(i))) { elemCount.put(word.charAt(i), elemCount.get(word.charAt(i)) + 1); } else { elemCount.put(word.charAt(i), 1); } } } ArrayList<Character> sortedElems = new ArrayList<>(); elemCount.entrySet().stream().sorted(Collections.reverseOrder (Map.Entry.comparingByValue())).forEach(entry -> { for (int i = 1; i <= entry.getValue(); i++) { sortedElems.add(entry.getKey()); } } ); System.out.println(sortedElems);
Advertisement
Answer
try the below code:
public static void main(String[] args){ List<String> list = new ArrayList<String>(); list.add("apple"); list.add("banana"); list.add("orange"); System.out.println(leastFrequentString(list)); } private static Set<String> leastFrequentString(List<String> list){ Map<String, Integer> mapStringToFrequency = new HashMap<>(); for(String s:list){ Map<Character, Integer> mapCharacterToFrequency = wordFrequency(s); int totalScore = 0; for(Character c:mapCharacterToFrequency.keySet()){ if(mapCharacterToFrequency.get(c)>1){ totalScore+=1; } } mapStringToFrequency.put(s,totalScore); } HashMap sortByValue = sortByValue(mapStringToFrequency); return sortByValue.keySet(); } private static Map<Character,Integer> wordFrequency(String s){ Map<Character, Integer> mapCharacterToFrequency = new HashMap<Character, Integer>(); for(Character c: s.toCharArray()){ if(mapCharacterToFrequency.containsKey(c)){ int frequency = mapCharacterToFrequency.get(c); frequency +=1; mapCharacterToFrequency.replace(c,frequency); }else{ mapCharacterToFrequency.put(c,1); } } return mapCharacterToFrequency; } private static LinkedHashMap<String, Integer> sortByValue(Map<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<>(hm.entrySet()); // Sort the list list.sort(Comparator.comparing(Map.Entry::getValue)); // put data from sorted list to HashMap LinkedHashMap<String, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; }