Я бы использовал подход с двумя наборами;
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);
}
}
В качестве альтернативы, вы также можете использовать один HashMap с HashMap.Key в качестве Integer и HashMap.Value в качестве счетчика для этого Integer.Затем, если вам позже потребуется рефакторинг, чтобы найти все экземпляры с одним вхождением, вы можете легко это сделать.
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)));
}
}
Будьте осторожны с NumberFormatExceptions и, в зависимости от вашей ситуации, вы можете обрабатывать их внутри циклаили вне цикла.