某单位将要组织一次旅游,已知各成员及其目的地(见“人员信息.txt”),要求根据人员信息,将各地的成员信息统一列出,以供统筹安排,并将结果输出到文件“人员信息2.txt”中。
注:题中不要求城市,或人员信息的顺序。
//人员信息.txt的内容如下(应为一个单独的文本文件):
赵一,北京
钱二,上海
孙三,南京
李四,北京
周小五,西安
吴天,南京
郑小七,上海
赵八,北京
王心凌,天津
刀郎,北京
例本题的输出应为:
北京
4
刀郎
李四
赵八
赵一
上海
2
钱二
郑小七
南京
2
孙三
吴天
西安
1
周小五
天津
1
王心凌
刚在csdn上帮你解决了。
FileReader fr = new FileReader("d:\\aa.txt"); //读取流
BufferedReader br = new BufferedReader(fr); //缓冲流
FileWriter fw=new FileWriter("d:\\a2.txt"); //输出流
BufferedWriter bw=new BufferedWriter(fw); //输出缓冲流
String tempStr = "";
// 定义map key为城市名 值为list集合 存储所有city
Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
while ((tempStr = br.readLine()) != null) {
String[] tmpStrArray = tempStr.split(",");//读一行 把之分解成数组
//取得城市名 并判断是否在map已存在
if (cityMap.containsKey(tmpStrArray[1])) { //存在的情况
cityMap.get(tmpStrArray[1]).add(tmpStrArray[0]);
} else {//不存在的情况
List<String> cityList = new ArrayList<String>();
cityList.add(tmpStrArray[0]);
cityMap.put(tmpStrArray[1], cityList);
}
}
br.close();//关闭流
//************输出操作
Set<String> sStr = cityMap.keySet(); //从map中取出城市set集合并遍历
for (Iterator iterator = sStr.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
bw.write(string);
bw.newLine();
List<String> cityOutList = cityMap.get(string);
Integer size=cityOutList.size(); //不是直接输出。必须用Integer包装类来保存
bw.write(size.toString());
bw.newLine();
for (Iterator iterator2 = cityOutList.iterator(); iterator2
.hasNext();) {
String tempStr2 = (String) iterator2.next();
bw.write(tempStr2);
bw.newLine();
}
bw.newLine();
}
bw.flush();
bw.close();
建立Map>集合
遍历文件1,一行一行读。
用逗号对行数据进行分割,将地区作为key,List人名称作为value,插入Map.
遍历结束。
遍历Map,输出到文件。