Reputation: 3847
Here I'm trying to read a text file which contains only integers.in every line.For eg:
1
2
3
1
I wrote the following code to read the text file. Code as shown below.
package fileread;
import java.io.*;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
try{
FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
}
}
Now I want to retrieve only those integers which repeated and display it to the user. In this case i want to display "1".
How can I implement this in Java??
Upvotes: 0
Views: 3341
Reputation: 1385
I would use the two set approach;
public static void main(String[] args) {
Set<Integer> result = new HashSet<Integer>();
Set<Integer> temp = new HashSet<Integer>();
try{
FileInputStream fstream=new FileInputStream("text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
if (!"".equals(str.trim())){
try {
Integer strInt = new Integer(str.trim());
if(temp.contains(strInt)){
result.add(strInt);
} else {
temp.add(strInt);
}
} catch (Exception e){
// usually NumberFormatException
System.err.println(e);
}
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
for(Integer resultVal : result){
System.out.println(resultVal);
}
}
Alternately, you could also use a single HashMap with the HashMap.Key as the Integer and the HashMap.Value as count for that Integer. Then if you later need to refactor to find all instances with a single occurrence then you can easily do that.
public static void main(String[] args) {
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
try{
FileInputStream fstream=new FileInputStream("text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
if (!"".equals(str.trim())){
try {
Integer strInt = new Integer(str.trim());
int val = 1;
if(frequency.containsKey(strInt)){
val = frequency.get(strInt).intValue() + 1;
}
frequency.put(strInt, val);
} catch (Exception e){
// usually NumberFormatException
System.err.println(e);
}
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
// this is your method for more than 1
for(Integer key : frequency.keySet()){
if (frequency.get(key).intValue() > 1){
System.out.println(key);
}
}
// This shows the frequency of values in the file.
for(Integer key : frequency.keySet()){
System.out.println(String.format("Value: %s, Freq: %s", key, frequency.get(key)));
}
}
Be careful of NumberFormatExceptions, and depending on your situation, you can either handle them inside the loop, or outside the loop.
Upvotes: 0
Reputation: 222
Something like this
package fileread;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
try{
FileInputStream fstream =
new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
String sproof = (String) ht.get(str.trim());
if (sproof != null && sproof.equals("1")) {
System.out.println(str);
} else {
ht.put(str.trim(), "1");
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
}
}
Upvotes: 0
Reputation: 2241
First off, I would define 1 list and 1 set of Integers, as below:
ArrayList<Integer> intList = new ArrayList<Integer>();
Set<Integer> duplicateIntSet = new HashSet<Integer>(); //Set is used to avoid duplicates
And then, I would check for duplicates and add 'em to respective lists, as below:
while((str=br.readLine())!=null){
if(!str.isEmpty()) {
Integer i = Integer.parseInt(str);
if(intList.contains(i)) {
duplicateIntSet.add(i);
} else {
intList.add(i);
}
}
}
Upvotes: 0
Reputation: 162771
package fileread;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> uniqueLines = new HashSet<String>();
Set<String> duplicatedLines = new HashSet<String>();
try{
FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
if (uniqueLines.contains(str)) {
if (!duplicatedLines.contains(str)) {
duplicatedLines.add(str);
System.out.println(str);
}
} else {
uniqueLines.add(str);
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
}
}
Note: Make sure your input doesn't have trailing whitespace on each line. Also, note that when the list gets long, this implementation is not particularly memory friendly.
Upvotes: 1
Reputation: 8582
In addition to the given answers, make sure you are converting your strings to integers (numbers) and catch the exception in case whatever comes from the file isn't a number. In this case I think you can safely ignore the exception because it's not relevant, but it's a good practice to check your input data.
Upvotes: 0
Reputation: 9266
Well, you can use an array with 10 slots which maps to a number from 0 to 9. For every line, you check what that number is and increment the value in the array accordingly. It would be something like this:
// Initialize the array
int[] numberArray = new int[10];
for (int i = 0 ; i < 10 ; i++) numberArray[i] = 0;
while((str=br.readLine())!=null){
int number = Integer.parseInt(str);
numberArray[number]++;
}
for (int i = 0 ; i < 10 ; i++) {\
if (numberArray[i] > 1) System.out.println(i);
}
Upvotes: 0
Reputation: 17621
Read the file entirely, save the lines to a data structure of your choice (map(key=line, value=count), array if only integers), enumerate the data structure and print these whose value is greater than 1 (if the value represents the count).
or on the fly: read the file, add entry to a set/list/array, if not contained in set/list/array, else print out line.
Upvotes: 0
Reputation: 1888
You need to read the value in an array and then find duplicate entries in that array.
Upvotes: 1