日期:2014-05-20 浏览次数:20701 次
public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("d:\\input.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String astr = br.readLine(); String bstr = null; Pattern p = Pattern.compile("\\d+"); List lista = new ArrayList(); List listb = new ArrayList(); while ((bstr = br.readLine()) != null) { String[] aarray = astr.split(" "); String[] barray = bstr.split(" "); if (aarray[0].equals(barray[0]) && astr.contains("Follower") && bstr.contains("Following")) { Matcher am = p.matcher(aarray[1]); while(am.find()){ lista.add(am.group()); } Matcher bm = p.matcher(barray[1]); while(bm.find()){ listb.add(bm.group()); } lista.retainAll(listb); if(lista.size() > 0){ System.out.print(barray[0] +" "); System.out.print("["); for(int i = 0;i < lista.size();i++){ System.out.print(lista.get(i)); if(i != lista.size() - 1){ System.out.print(","); } } System.out.println("]"); } lista.clear(); listb.clear(); } astr = bstr; } br.close(); }
------解决方案--------------------
呵呵。我也来写一个,欢迎大家指评。
import java.io.*; import java.util.*; public class InputTest { public static void main(String[] args) throws IOException { File file = new File("D:/input.txt"); Scanner in = new Scanner(file); Map<String, String> map_root = new HashMap<String, String>(); Map<String, String> map_rs = new HashMap<String, String>(); String[] str;String str1; while (in.hasNextLine()) { str = in.nextLine().split(" "); if (map_root.containsKey(str[0])) map_root.put(str[0], map_root.get(str[0]) + " " + str[1]); else map_root.put(str[0], str[1]); } for (String key : map_root.keySet()) { str1 = map_root.get(key); String[] str2,str5,str6;String str3,str4; if (str1.indexOf(" ") != -1) { str2 = str1.split(" "); str3 = str2[0].substring(str2[0].indexOf("[") + 1, str2[0].lastIndexOf("]")); str4 = str2[1].substring(str2[1].indexOf("[") + 1, str2[1].lastIndexOf("]")); str5 = str3.split(","); str6 = str4.split(","); for (int j = 0; j < str5.length; j++) { if ("" == str5[j]) continue; for (int p = 0; p < str6.length; p++) { if ("" == str6[p]) continue; if (str5[j].equals(str6[p])) { if (map_rs.containsKey(key)) map_rs.put(key, map_rs.get(key) + "," + str5[j]); else map_rs.put(key, str5[j]); } } } } } StringBuffer buf=new StringBuffer(); for(String key:map_rs.keySet()){ buf.append(key+" "+"["+map_rs.get(key)+"]"+"\r\n"); } FileOutputStream os=new FileOutputStream(new File("d:/output.txt")); os.write(buf.toString().getBytes(), 0, buf.toString().getBytes().length); } }