Created
July 2, 2011 12:55
-
-
Save gpiancastelli/1060033 to your computer and use it in GitHub Desktop.
Print the letters of an input string in alphabetic order alongside their frequency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
public class Letters { | |
public static void main(String[] args) { | |
String input = args[0].toLowerCase(); | |
Map<Character, Integer> letterFrequency = new HashMap<Character, Integer>(); | |
for (int i = 0; i < input.length(); i++) { | |
char c = input.charAt(i); | |
if (!Character.isLetter(c)) | |
continue; | |
if (letterFrequency.containsKey(c)) { | |
int frequency = letterFrequency.get(c); | |
letterFrequency.put(c, ++frequency); | |
} else | |
letterFrequency.put(c, 1); | |
} | |
List<Character> letters = | |
new ArrayList<Character>(letterFrequency.keySet()); | |
Collections.sort(letters); | |
for (Character letter : letters) | |
System.out.printf("%s: %2d%n", letter, letterFrequency.get(letter)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment