Adobe Interview Question
Quality Assurance EngineersCountry: United States
Interview Type: In-Person
public static void collectDataFromFileAndPutIntoMap(String loc)
{
Map<String,Integer> m=new HashMap<String,Integer>();
File f=new File(loc);
try {
BufferedReader br=new BufferedReader(new FileReader(f));
String s=null;
String[] tok;
while((s=(br.readLine()))!=null)
{
for(String s1: s.split(" "))
{
if(m.get(s1)==null)
m.put(s1,1);
else
m.put(s1, m.get(s1)+1);
}
iterateOverHashMap(m);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void iterateOverHashMap(Map<String, Integer> m) {
Iterator it=m.entrySet().iterator();
while(it.hasNext())
{
Map.Entry pairs=(Map.Entry) it.next();
System.out.println(pairs.getKey() + "----" + pairs.getValue());
}
}
This is definitely not the most efficient solution but still a working one at that :)
class FileCountWords {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Enter File name with path: ");
String filename = input.next();
File f = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(f));
StringBuffer buffer = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
buffer.append(str);
buffer.append(" ");
}
ArrayList<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(buffer.toString()
.toLowerCase());
while (st.hasMoreTokens()) {
String s = st.nextToken();
list.add(s);
}
while (!list.isEmpty()) {
int i = 0;
String uniqueStr = list.get(i);
int index = list.lastIndexOf(uniqueStr);
int uniqueStrCount = 1;
while (i != index) {
uniqueStrCount++;
list.remove(index);
index = list.lastIndexOf(uniqueStr);
}
System.out.println("count of word " + "-" + uniqueStr + "-"
+ " in the file is : " + uniqueStrCount);
list.remove(i);
i++;
}
}
}
package pracise;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class fileReader {
public static void main(String[] args) throws IOException{
HashMap<String, Integer> h = new HashMap<String, Integer>();
BufferedReader input = new BufferedReader(new FileReader(new File("//Users//a")));
try {
String line = null;
while ((line = input.readLine()) != null) {
String[] l = line.split(" ");
for(String s : l){
if(h.containsKey(s)){
int counter = h.get(s);
counter++;
h.put(s, counter);
}else{
h.put(s, 1);
}
}
}
} finally {
input.close();
}
System.out.println(h);
}
}
- Srinivas_Java April 18, 2013