1,s,28
2,a,35
3,a,28
4,b,35
5,s,28
6,a,35
7,c,28
8,d,35
9,c,28
10,c,28
11,c,28
12,c,28
13,c,28java
package cglib;ide
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StringNumber {
//首先取出每行的内容,并放入一个list中,而后取出每一行的name分别放入set和list中,计算出重复的个数,最后进行排序。
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
InputStreamReader is = new FileReader("D:\\文件\\QC处理\\2016年11月\\c.txt");
BufferedReader br = new BufferedReader(is);
List<String> list = new ArrayList<String>();
String str = "";
// 读取文件,把取出的每一行放入到list中
while ((str = br.readLine()) != null) {
list.add(str);
}
// 使用set存放name 不包括重复,使用list 存放全部的name
Set<String> set = new HashSet<String>();
List<String> listname = new ArrayList<String>();
for (String s : list) {
String[] sa = s.split(",");
set.add(sa[1]);
listname.add(sa[1]);
}
// 获取重复name的数目
List<P> Plist = new ArrayList<P>();
for (String setstr : set) {
int count = 0;
for (int j = 0; j < listname.size(); j++) {this
if (setstr.equals(listname.get(j))) {
count++;
}
}
if (count > 1) {
Plist.add(new P(count, setstr));
// 这个是对于Comparable 接口的
Collections.sort(Plist);
}
}
for (P p : Plist) {
System.out.println(p.count + "===" + p.name);
}spa
}
}排序
// 建立一个类,并排序
class P implements Comparable<P> {
int count;接口
String name;get
public P(int count, String name) {
this.count = count;
this.name = name;
}it
@Override
public int compareTo(P o) {
if (this.count > o.count) {
return 1;
} else {
return -1;
}
}
}io
输出:class
2===s
3===a
6===c
一些经验总结:
1.对于读取文件,你们要熟记BufferedReader类,他能够一次读取一行,在不少的笔试题会遇到这样的例子,可是判断读取结束的标志并非咱们平时所见的-1,而是null。
2.能够利用集合进行简化代码,好比list元素能够重复,可是set的元素不能够重复等
package cglib;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StringNumber {
/**
* 一、从相似以下的文本文件中读取出全部的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序
* name.txt文件内容以下
* 1,张三,28
2,李四,35
3,张三,28
4,王五,35
5,张三,28
6,李四,35
7,赵六,28
8,田七,35
*/
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\文件\\QC处理\\2016年11月\\c.txt"), "GBK");
//使用BufferedReader一次能够读取一行,判断是否为结尾用null判断
BufferedReader bf = new BufferedReader(isr);
String str= bf.readLine();
List<String> names = new ArrayList<String>();
while(str!=null){ //1,张三,28
String []st=str.split(",");
names.add(st[1]);
//只把姓名添加进去就能够了
str= bf.readLine();
}
Set<String> name =
new HashSet<String>(names); //[赵六, 张三, 田七, 李四, 王五]
//因为set集合是不容许有重复的元素的,因此能够用set集合去重
for(String set :name){
String temp=set;
int num=0;
for(String s : names) //list集合里有不少重复的。对每次迭代的元素,要是次数大于2就表示重复
{
if(temp.equals(s)){
num++;
}
}
if(num>=2){
System.out.println(temp+"重复次数:"+num);
}
}
}
}
输出:
李四重复次数:2 张三重复次数:3