我想更改给定图表的形式。该图表的形式为userID,关注者数量,follower1,follower2,.. followerN,delimiter' ---',userID2,...等。
我必须使用表单的第二个文件中的位置值替换关注者 ID1 place1 ID2 place2 ....
匹配ID。
因此,我想检查每次跟随者ID是否存在于集合中。 我的图表和我寻找追随者ID的集合都是巨大的。
有没有比我给你的方式更有效的方式?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.*;
public class Changer {
public static void main(String[] args) {
Set set = new HashSet();
int[][] users=new int[61578415][];
try{
FileInputStream fstream2 = new FileInputStream(args[0]);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine2;
while ((strLine2 = br2.readLine()) != null) {
set.add(strLine2);
}
in2.close();
fstream2.close();}
catch (Exception e){
System.err.println("Error: " + e.getMessage()+"!\n"+e.toString()+"!\n");
e.printStackTrace();
System.exit(-1);
}
try{
FileInputStream fstream = new FileInputStream("InputGraph.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int flag=0;
int pos=0;
FileWriter fstream3 = new FileWriter("OutputGraph.txt");
BufferedWriter out = new BufferedWriter(fstream3);
int currentUser=0,counter=0;
int theNum=0;
while ((strLine = br.readLine()) != null) {
if(strLine.equals("---")){
if(counter!=pos){
System.out.println("Error reading graph");
System.out.println("For:"+currentUser);
System.exit(-1);
}
flag=0;
pos=0;
continue;
}
theNum=Integer.parseInt(strLine);
if (flag==0){
out.write("---"+"\n");
out.write(""+theNum);
out.write("\n");
currentUser=theNum;
flag+=1;
}
else if (flag==1){
counter=theNum;
users[currentUser]=new int [counter];
flag+=1;
out.write(""+theNum+"\n");
}
else{
users[currentUser][pos]=theNum;
++pos;
Iterator it = set.iterator();
while (it.hasNext()) {
Object element = it.next();
String[] arr = (String.valueOf(element)).split(" ");
if (Integer.parseInt(arr[0])==theNum)
{theNum=Integer.parseInt(arr[1]);break;}
}
out.write(""+theNum);
out.write("\n");
}
}
in.close();
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.println("Graph has been read");
System.gc();
System.gc();
System.out.println("Finished");
}
}
答案 0 :(得分:1)
在内部对intersection
进行for循环会更有效率,这样你就不会分裂和解析这么多:
Iterator it = set.iterator();
while (it.hasNext()) {
Object element = it.next();
String[] arr = (String.valueOf(element)).split(" ");
int arr0 = Integer.parseInt(arr[0]);
int arr1 = Integer.parseInt(arr[1]);
for (int integer : intersection) {
if (arr0 == integer) {
out.write(integer + " " + arr1 + "\n");
}
}
}
但是这会改变写入的顺序。
然而我怀疑您可能会将其加载到(或仅替换)HashMap
或SparseArray
中。很难说出你给出的信息。
答案 1 :(得分:0)
对于整数检测,您可以使用与 instanceof 的比较,但您必须使用对象而不是基元,例如:
Integer a=Integer.parseInt("12345");
if(a instanceof Integer){
System.out.println("We have an integer !");
}
整数检测的另一种方法是覆盖equals方法。