Advertisement
MrPolywhirl

ReplaceMap.java

Dec 3rd, 2013
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class ReplaceMap {
  4.     private static Map<String, String> replacements;
  5.  
  6.     static {
  7.         replacements = new HashMap<String, String>();
  8.         replacements.put("ab", "Apple");
  9.         replacements.put("bac", "Banana");
  10.         replacements.put("cdea", "Cantalope");
  11.         replacements.put("dabcd", "Date");
  12.     }
  13.    
  14.     public ReplaceMap() {
  15.         String phrase = "ab bac cdea dabcd ab bac cdea dabcd";
  16.  
  17.         System.out.println(replace(phrase, replacements));
  18.     }
  19.    
  20.     public static List<String> asSortedList(Collection<String> c) {
  21.         List<String> list = new ArrayList<String>(c);
  22.         Collections.sort(list, new Comparator<String>() {
  23.             @Override
  24.             public int compare(String a, String b) {
  25.                 if (a.length() < b.length()) {
  26.                     return 1;
  27.                 } else if (a.length() > b.length()) {
  28.                     return -1;
  29.                 } else {
  30.                     return a.compareTo(b);
  31.                 }
  32.             }
  33.         });
  34.        
  35.         return list;
  36.     }
  37.    
  38.     public static String replace(String it, Map<String, String> map) {
  39.         StringBuilder sb = new StringBuilder();
  40.         List<String> sortedKeys = asSortedList(map.keySet());
  41.         System.out.printf("KEYS SORTED: %s\n", sortedKeys);
  42. next:   while (it.length() > 0) {
  43.             for (String k : sortedKeys) {
  44.                 if (it.startsWith(k)) {
  45.                     // We have a match!
  46.                     sb.append(map.get(k));
  47.                     it = it.substring(k.length(), it.length());
  48.                     continue next;
  49.                 }
  50.             }
  51.             // no match, advance one character
  52.             sb.append(it.charAt(0));
  53.             it = it.substring(1, it.length());
  54.         }
  55.        
  56.         return sb.toString();
  57.     }
  58.    
  59.     public static void main (String[] args) throws java.lang.Exception {
  60.         new ReplaceMap();
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement