import java.util.HashMap; import java.util.List; import java.util.Map; /** * This utility class contains some methods for lists of strings. * * @author Franck van Breugel */ public class Test2A { private Test2A() {} /** * Returns the size of the given list. * * @param list a list of strings. * @pre. list != null * @return the size of the given list. */ public static int size(List list) { return list.size(); } /** * Returns the first element of the given list. * * @param list a list of strings. * @return the first element of the given list. * @throws IllegalArgumentException if the list is null or has size zero. */ public static String first(List list) throws IllegalArgumentException { if (list == null || list.size() == 0) { throw new IllegalArgumentException(); } else { return list.get(0); } } /** * Returns the length of a longest string in the given list. * * @param list a list of strings. * @pre. list != null && list.size() > 0 * @return the length of a longest string in the given list. */ public static int lengthOfLongestString(List list) { int length = 0; for (String element : list) { length = Math.max(length, element.length()); } return length; } /** * Returns the string of the given list with the most occurrences of * the same character. If multiple strings have the most occurrences of * the same character, of those strings the one which is smallest in the * lexicographic order (as usesd for example in a dictionary) is returned. * For example, consider the following list.
* ["aaa", "abab", "accacc", "beeee"]
* The strings "accacc" and "beeee" both contain four occurrences of the * same character. Since "accacc" is smaller than "beeee" in the lexicographic * order, "accac" would be returned by this method. * * @param list a list of strings. * @pre. list != null && list.size() > 0 * @return the string of the given list with the most occurrences of * the same character. */ public static String max(List list) { int maxCount = 0; String maxWord = null; for (String word : list) { Map characterCount = new HashMap(); for (int i = 0; i < word.length(); i++) { char letter = word.charAt(i); int count; if (!characterCount.containsKey(letter)) { count = 0; } else { count = characterCount.get(letter); } characterCount.put(letter, count + 1); } int count = 0; for (Character c : characterCount.keySet()) { if (characterCount.get(c) > count) { count = characterCount.get(c); } } if (count > maxCount || (count == maxCount && (maxWord == null || word.compareTo(maxWord) < 0))) { maxWord = word; maxCount = count; } } return maxWord; } }