stream流用代码对汉字怎么排序
时间: 2023-05-23 17:01:21 浏览: 134
第二章代码汇总.zip
对于汉字的排序,需要先将汉字转换为拼音,然后再进行比较。以下是一个示例的排序代码:
```java
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
// 读取文件
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
// 临时存储字符串
String line;
List<String> list = new ArrayList<String>();
// 逐行读取,并存储到List中
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
// 排序
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 将汉字转换为拼音再进行比较
return ChineseToPinyin.convert(o1).compareTo(ChineseToPinyin.convert(o2));
}
});
// 写出文件
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("output.txt"))));
for (String s : list) {
bw.write(s);
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ChineseToPinyin {
private HanyuPinyinOutputFormat format;
private String[] pinyin;
public String getPinyin(String src) {
char[] srcChar = src.toCharArray();
String[] tmp;
String t = "";
try {
for (int i = 0; i < srcChar.length; i++) {
tmp = PinyinHelper.toHanyuPinyinStringArray(srcChar[i], format);
if (tmp == null) {
t += srcChar[i];
} else {
t += tmp[0];
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return t;
}
public static String convert(String input) {
ChineseToPinyin pt = new ChineseToPinyin();
pt.format = new HanyuPinyinOutputFormat();
pt.format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
pt.format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
pt.format.setVCharType(HanyuPinyinVCharType.WITH_V);
return pt.getPinyin(input);
}
}
```
输入的汉字会按照拼音的排序写入到 output.txt 中。
阅读全文