用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2 /
/…
(3)按照上面的打印格式将内容写入到D:\count.txt文件中(要求用高效流)
实现代码:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class HomeWork1 {
public static void main(String[] args) throws IOException {
String s = "If you want to change your fate I think you must come to the dark horse to learn java";
function(s);
}
public static void function(String s) throws IOException {
String[] sArr = s.split(" ");
HashMap<String, Integer> hm = new HashMap<>();
for(String string : sArr) {
if(!hm.containsKey(string))
hm.put(string, 1);
else {
int value = hm.get(string);
value++;
hm.put(string, value);
}
}
List<String> list = new ArrayList<>();//新建一个过度数组储存单词
for(String key : hm.keySet()) {
list.add(key);
}
Collections.sort(list);//将储存的单词排序
Map<String, Integer> orderMap = new LinkedHashMap<String, Integer>();//新建一个有序的LinkedHashMap
for(String key : list) {
orderMap.put(key, hm.get(key));//按顺序将排序后的单词和对应个数存入LinkedHashMap中
}
write(orderMap);
}
//
public static void write(Map<String, Integer> map) throws IOException {
BufferedWriter bfw = new BufferedWriter(new FileWriter("D:\\360MoveData\\Users\\xucc\\Desktop\\count.txt"));
for(String key : map.keySet()) {
bfw.write(key+"="+map.get(key));
bfw.newLine();//写入一个,换一行
bfw.flush();
}
bfw.close();
}
}
输出结果: