Wednesday, September 10, 2014

Java program to remove duplicate word from a file without using Collection framework.

2:38 PM

In an interview with Oracle one of my friend found this problem how to remove duplicate occurrence of a given word from a file without using collection framework. Since, Set interface of Collection API is a best and easy choice in the case of no duplication. But what to do in the problems when we are asked not to use Collection.

INPUT: TEST TEST TEST RESULT RESULT TEST

WORD TO REMOVE DUPLICATE: TEST

OUTPUT: TEST RESULT RESULT 

Java program 

//RemoveDuplicate.java


import java.io.*;
class RemoveDuplicate 
{
public final String INPUT_FILE="Test.txt";
public final String OUTPUT_FILE="Output.txt";
public int count=0;

public void checkDuplicate(String wordToCheck) throws Exception
{
BufferedReader br=new BufferedReader(new FileReader(INPUT_FILE));
BufferedWriter bw=new BufferedWriter(new FileWriter(OUTPUT_FILE));
StringBuilder sb=new StringBuilder();
while(br.ready())
{
sb=sb.append(br.readLine());
}

String data=sb.toString();
String values[]=data.split(" ");
for(int i=0; i<values.length;i++)
{
String arrVal=values[i].trim();
if(arrVal.equalsIgnoreCase(wordToCheck))
{
count=count+1;
if(count>1)
{
continue;
}
else
{
bw.write(arrVal+" ");
}
}
else
{
bw.write(arrVal+" ");
}
}

bw.flush();
br.close();
bw.close();
}

public static void main(String [] args)throws Exception
{
new RemoveDuplicate().checkDuplicate("Result");
}
}

Note: Make sure input file is available at given location. 


Input file 
Text.txt
                                   
Output file


Output.Txt

Above java code file can be downloaded by clicking here


0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy