中文字符串比较案例

import java.io.*;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;

class Student{
	String name = null;
	String adress = null;
	Student(){
	}
	Student(String name, String adress) {
		this.name = name;
		this.adress = adress;
	}
}
class DoMap{
	static CollatorComparator comparator = new CollatorComparator();
	static TreeMap<String, TreeSet<String>> map = new TreeMap<String, TreeSet<String>>(comparator);
	public static void myGet(){
		
		for(Iterator it=map.keySet().iterator();it.hasNext();){
			String s =(String)it.next();
System.out.println(s);
System.out.println(map.get(s).size());
			for(Iterator its = map.get(s).iterator();its.hasNext();){
System.out.println(its.next());				
			}
System.out.println();				
		}
		
	}
	public static void myPut(Student s){
		if(map.containsKey(s.adress)){
			map.get(s.adress).add(s.name);
			return;
		}
		else{
			TreeSet<String> set= new TreeSet<String>(comparator);
			set.add(s.name);
			map.put(s.adress,set);
			return;
		}
	}
}
class ReadTxt {
	Student stu = new Student();
	public void read() {
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader("test.txt");
			br = new BufferedReader(fr);
			String s = null;
			String str[] = new String[2];
			int i = 0;
			while ((s = br.readLine())!=null) {
				str = s.split(",");
				stu = new Student(str[0],str[1]);
				DoMap.myPut(stu);
				i++;
			}
			DoMap.myGet();
		} catch (Exception e) {
			e.getStackTrace();
		} finally {
			try {
				br.close();
				fr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
class CollatorComparator implements Comparator{
	Collator collator = Collator.getInstance();
	public int compare(Object element1, Object element2){
	    CollationKey key1 = collator.getCollationKey(element1.toString());
	    CollationKey key2 = collator.getCollationKey(element2.toString());
	    return key1.compareTo(key2);
	}
}
public class Demo {
	public static void main(String[] args) {
		ReadTxt rt = new ReadTxt();
		rt.read();
	}
}
//TreeSet,TreeMap自动比较中文字符串按拼音字典序排序。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值