Question:
Given path to file or directory. Assume all are text.
Implement Iterator which transverse over all the word in the file.
My Solution: Didn't got time to complete whole solution but I explained interviewer the approach. Is it the right way to implement iterartor?
public class DesignIterator {
static List<String> words = new ArrayList<>();
public static void buildWords(String line) {
String output ="";
for(char c: line.toCharArray()) {
if(c==' ' && !output.isEmpty()) {
words.add(output);
output = "";
continue;
}
else if(c!=' ') {
output+=c;
}
}
if(!output.isEmpty()) {
words.add(output);
}
}
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("resources/File.txt"));
String content = br.readLine();
while(content!=null) {
buildWords(content);
content = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}
//System.out.println(words);
List<Iterator> input= new ArrayList<>();
input.add(words.iterator());
WordIterator iterateWords = new WordIterator(input);
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
System.out.println(iterateWords.next());
}}
public class WordIterator {
List<Iterator> wordsList;
int count = 0;
int size=0;
public WordIterator(List<Iterator> words) {
this.wordsList=words;
size = wordsList.size();
}
public Object next() {
if(wordsList!=null) {
Iterator itr = wordsList.get(count % size);
if(itr.hasNext()) {
return itr.next();
}
}
return null;
}}