11. Collections and Maps

11.1
 import java.util.*; public class UniqueCharacterCounter { /** * A cache, mapping strings to count results. The count values are * stored as Integer objects within the map. */ static Map globalCache = new HashMap(); public static int countUniqueCharacters(String aString) { Object cachedResult = globalCache.get(aString); if (cachedResult != null) return ((Integer) cachedResult).intValue(); // Result was not in the cache, calculate it. int length = aString.length(); Set occurred = new TreeSet(); Set duplicates = new TreeSet(); // Identify occurrences and duplicates for each character in string: for (int i=0; i<length;i++) { Character character = new Character(aString.charAt(i)); if (duplicates.contains(character)) continue; ...

Get Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.