1 55 package org.lateralnz.common.util; 56 57 import java.util.HashMap ; 58 import java.util.Set ; 59 import java.util.Iterator ; 60 import java.util.regex.Matcher ; 61 import java.util.regex.Pattern ; 62 63 67 public class FilteredIterator implements Iterator { 68 69 private Pattern ipat; 70 private Pattern epat; 71 private Iterator iter; 72 73 private boolean hasNextProcessed = false; 74 private boolean hasNext = false; 75 private Object next = null; 76 77 public FilteredIterator(Set keyset, String incregex, String excregex) { 78 ipat = Pattern.compile(incregex); 79 epat = Pattern.compile(excregex); 80 iter = keyset.iterator(); 81 } 82 83 private Object getNext() { 84 String key; 85 while (iter.hasNext()) { 86 key = (String )iter.next(); 87 Matcher imat = ipat.matcher(key); 88 Matcher emat = epat.matcher(key); 89 if (imat.matches() && !emat.matches()) { 90 return key; 91 } 92 } 93 return null; 94 } 95 96 public boolean hasNext() { 97 if (!hasNextProcessed) { 98 next = getNext(); 99 if (next != null) { 100 hasNext = true; 101 return true; 102 } 103 } 104 return hasNext; 105 } 106 107 public Object next() { 108 hasNext = false; 109 if (next != null) { 110 Object rtn = next; 111 next = null; 112 return rtn; 113 } 114 else { 115 return getNext(); 116 } 117 } 118 119 public void remove() { 120 throw new UnsupportedOperationException (); 121 } 122 123 public static final void main(String [] args) throws Exception { 124 HashMap hm = new HashMap (); 125 hm.put("a/test1", ""); 126 hm.put("a/hello2", ""); 127 hm.put("a/test4", ""); 128 hm.put("a/tst5", ""); 129 hm.put("b/", ""); 130 hm.put("b/test18", ""); 131 hm.put("b/test3", ""); 132 hm.put("b/e/test19", ""); 133 hm.put("c/test2", ""); 134 hm.put("c/whattest52", ""); 135 136 FilteredIterator fi = new FilteredIterator(hm.keySet(), "b/[^/]*", "b/|"); 137 while (fi.hasNext()) { 138 System.out.println(fi.next()); 139 } 140 } 141 } 142 | Popular Tags |